home *** CD-ROM | disk | FTP | other *** search
/ Internet E-Mail Workshop / Internet E-Mail Workshop.iso / info / cfaq0593. < prev    next >
Text File  |  1993-11-24  |  146KB  |  3,233 lines

  1.  
  2. From: scs@adam.mit.edu (Steve Summit)
  3. To:   Matthew.Hunt@p2.f3.n2616.z1.fidonet.org
  4. Date: Thu, 20 May 93 09:03:42 -0400
  5.  
  6. Here is the latest version of the comp.lang.c FAQ list.  You
  7. might also want to watch for newer versions in comp.lang.c, near
  8. the first of each month (see also the last question).
  9.  
  10. Newsgroups: comp.lang.c,comp.answers,news.answers
  11. From: scs@adam.mit.edu (Steve Summit)
  12. Subject: comp.lang.c Answers to Frequently Asked Questions (FAQ List)
  13. Message-ID: <1s387bINNrot@senator-bedfellow.MIT.EDU>
  14. Followup-To: poster
  15. Supersedes: <1pdstkINN3aj@senator-bedfellow.MIT.EDU>
  16. Reply-To: scs@adam.mit.edu
  17. X-Archive-Name: C-faq/faq
  18. Date: 3 May 1993 13:54:51 GMT
  19. X-Last-Modified: May 2, 1993
  20. Expires: 3 Jun 1993 00:00:00 GMT
  21. Lines: 3210
  22.  
  23. [Last modified May 2, 1993 by scs.]
  24.  
  25. Certain topics come up again and again on this newsgroup.  They are good
  26. questions, and the answers may not be immediately obvious, but each time
  27. they recur, much net bandwidth and reader time is wasted on repetitive
  28. responses, and on tedious corrections to the incorrect answers which are
  29. inevitably posted.
  30.  
  31. This article, which is posted monthly, attempts to answer these common
  32. questions definitively and succinctly, so that net discussion can move
  33. on to more constructive topics without continual regression to first
  34. principles.
  35.  
  36. No mere newsgroup article can substitute for thoughtful perusal of a
  37. full-length tutorial or language reference manual.  Anyone interested
  38. enough in C to be following this newsgroup should also be interested
  39. enough to read and study one or more such manuals, preferably several
  40. times.  Some vendors' compiler manuals are unfortunately inadequate; a
  41. few even perpetuate some of the myths which this article attempts to
  42. refute.  Several noteworthy books on C are listed in this article's
  43. bibliography.  Many of the questions and answers are cross-referenced to
  44. these books, for further study by the interested and dedicated reader
  45. (but beware of ANSI vs. ISO C Standard section numbers; see question
  46. 5.1).
  47.  
  48. If you have a question about C which is not answered in this article,
  49. first try to answer it by checking a few of the referenced books, or by
  50. asking knowledgeable colleagues, before posing your question to the net
  51. at large.  There are many people on the net who are happy to answer
  52. questions, but the volume of repetitive answers posted to one question,
  53. as well as the growing number of questions as the net attracts more
  54. readers, can become oppressive.  If you have questions or comments
  55. prompted by this article, please reply by mail rather than following up
  56. -- this article is meant to decrease net traffic, not increase it.
  57.  
  58. Besides listing frequently-asked questions, this article also summarizes
  59. frequently-posted answers.  Even if you know all the answers, it's worth
  60. skimming through this list once in a while, so that when you see one of
  61. its questions unwittingly posted, you won't have to waste time
  62. answering.
  63.  
  64. This article is always being improved.  Your input is welcomed.  Send
  65. your comments to scs@adam.mit.edu, scs%adam.mit.edu@mit.edu, and/or
  66. mit-eddie!adam.mit.edu!scs; this article's From: line may be unusable.
  67.  
  68. The questions answered here are divided into several categories:
  69.  
  70.          1. Null Pointers
  71.          2. Arrays and Pointers
  72.          3. Memory Allocation
  73.          4. Expressions
  74.          5. ANSI C
  75.          6. C Preprocessor
  76.          7. Variable-Length Argument Lists
  77.          8. Boolean Expressions and Variables
  78.          9. Structs, Enums, and Unions
  79.         10. Declarations
  80.         11. Stdio
  81.         12. Library Subroutines
  82.         13. Lint
  83.         14. Style
  84.         15. Floating Point
  85.         16. System Dependencies
  86.         17. Miscellaneous (Fortran to C converters, YACC grammars, etc.)
  87.  
  88. Herewith, some frequently-asked questions and their answers:
  89.  
  90.  
  91. Section 1. Null Pointers
  92.  
  93. 1.1:    What is this infamous null pointer, anyway?
  94.  
  95. A:      The language definition states that for each pointer type, there
  96.         is a special value -- the "null pointer" -- which is
  97.         distinguishable from all other pointer values and which is not
  98.         the address of any object.  That is, the address-of operator &
  99.         will never yield a null pointer, nor will a successful call to
  100.         malloc.  (malloc returns a null pointer when it fails, and this
  101.         is a typical use of null pointers: as a "special" pointer value
  102.         with some other meaning, usually "not allocated" or "not
  103.         pointing anywhere yet.")
  104.  
  105.         A null pointer is conceptually different from an uninitialized
  106.         pointer.  A null pointer is known not to point to any object; an
  107.         uninitialized pointer might point anywhere.  See also questions
  108.         3.1, 3.11, and 17.1.
  109.  
  110.         As mentioned in the definition above, there is a null pointer
  111.         for each pointer type, and the internal values of null pointers
  112.         for different types may be different.  Although programmers need
  113.         not know the internal values, the compiler must always be
  114.         informed which type of null pointer is required, so it can make
  115.         the distinction if necessary (see below).
  116.  
  117.         References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
  118.         Sec. 5.3 p. 91; ANSI Sec. 3.2.2.3 p. 38.
  119.  
  120. 1.2:    How do I "get" a null pointer in my programs?
  121.  
  122. A:      According to the language definition, a constant 0 in a pointer
  123.         context is converted into a null pointer at compile time.  That
  124.         is, in an initialization, assignment, or comparison when one
  125.         side is a variable or expression of pointer type, the compiler
  126.         can tell that a constant 0 on the other side requests a null
  127.         pointer, and generate the correctly-typed null pointer value.
  128.         Therefore, the following fragments are perfectly legal:
  129.  
  130.                 char *p = 0;
  131.                 if(p != 0)
  132.  
  133.         However, an argument being passed to a function is not
  134.         necessarily recognizable as a pointer context, and the compiler
  135.         may not be able to tell that an unadorned 0 "means" a null
  136.         pointer.  For instance, the Unix system call "execl" takes a
  137.         variable-length, null-pointer-terminated list of character
  138.         pointer arguments.  To generate a null pointer in a function
  139.         call context, an explicit cast is typically required, to force
  140.         the 0 to be in a pointer context:
  141.  
  142.                 execl("/bin/sh", "sh", "-c", "ls", (char *)0);
  143.  
  144.         If the (char *) cast were omitted, the compiler would not know
  145.         to pass a null pointer, and would pass an integer 0 instead.
  146.         (Note that many Unix manuals get this example wrong.)
  147.  
  148.         When function prototypes are in scope, argument passing becomes
  149.         an "assignment context," and most casts may safely be omitted,
  150.         since the prototype tells the compiler that a pointer is
  151.         required, and of which type, enabling it to correctly convert
  152.         unadorned 0's.  Function prototypes cannot provide the types for
  153.         variable arguments in variable-length argument lists, however,
  154.         so explicit casts are still required for those arguments.  It is
  155.         safest always to cast null pointer function arguments, to guard
  156.         against varargs functions or those without prototypes, to allow
  157.         interim use of non-ANSI compilers, and to demonstrate that you
  158.         know what you are doing.  (Incidentally, it's also a simpler
  159.         rule to remember.)
  160.  
  161.         Summary:
  162.  
  163.                 Unadorned 0 okay:       Explicit cast required:
  164.  
  165.                 initialization          function call,
  166.                                         no prototype in scope
  167.                 assignment
  168.                                         variable argument in
  169.                 comparison              varargs function call
  170.  
  171.                 function call,
  172.                 prototype in scope,
  173.                 fixed argument
  174.  
  175.         References: K&R I Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R II
  176.         Sec. A7.10 p. 207, Sec. A7.17 p. 209; H&S Sec. 4.6.3 p. 72; ANSI
  177.         Sec. 3.2.2.3 .
  178.  
  179. 1.3:    What is NULL and how is it #defined?
  180.  
  181. A:      As a matter of style, many people prefer not to have unadorned
  182.         0's scattered throughout their programs.  For this reason, the
  183.         preprocessor macro NULL is #defined (by <stdio.h> or
  184.         <stddef.h>), with value 0 (or (void *)0, about which more
  185.         later).  A programmer who wishes to make explicit the
  186.         distinction between 0 the integer and 0 the null pointer can
  187.         then use NULL whenever a null pointer is required.  This is a
  188.         stylistic convention only; the preprocessor turns NULL back to 0
  189.         which is then recognized by the compiler (in pointer contexts)
  190.         as before.  In particular, a cast may still be necessary before
  191.         NULL (as before 0) in a function call argument.  (The table
  192.         under question 1.2 above applies for NULL as well as 0.)
  193.  
  194.         NULL should _only_ be used for pointers; see question 1.8.
  195.  
  196.         References: K&R I Sec. 5.4 pp. 97-8; K&R II Sec. 5.4 p. 102; H&S
  197.         Sec. 13.1 p. 283; ANSI Sec. 4.1.5 p. 99, Sec. 3.2.2.3 p. 38,
  198.         Rationale Sec. 4.1.5 p. 74.
  199.  
  200. 1.4:    How should NULL be #defined on a machine which uses a nonzero
  201.         bit pattern as the internal representation of a null pointer?
  202.  
  203. A:      Programmers should never need to know the internal
  204.         representation(s) of null pointers, because they are normally
  205.         taken care of by the compiler.  If a machine uses a nonzero bit
  206.         pattern for null pointers, it is the compiler's responsibility
  207.         to generate it when the programmer requests, by writing "0" or
  208.         "NULL," a null pointer.  Therefore, #defining NULL as 0 on a
  209.         machine for which internal null pointers are nonzero is as valid
  210.         as on any other, because the compiler must (and can) still
  211.         generate the machine's correct null pointers in response to
  212.         unadorned 0's seen in pointer contexts.
  213.  
  214. 1.5:    If NULL were defined as follows:
  215.  
  216.                 #define NULL (char *)0
  217.  
  218.         wouldn't that make function calls which pass an uncast NULL
  219.         work?
  220.  
  221. A:      Not in general.  The problem is that there are machines which
  222.         use different internal representations for pointers to different
  223.         types of data.  The suggested #definition would make uncast NULL
  224.         arguments to functions expecting pointers to characters to work
  225.         correctly, but pointer arguments to other types would still be
  226.         problematical, and legal constructions such as
  227.  
  228.                 FILE *fp = NULL;
  229.  
  230.         could fail.
  231.  
  232.         Nevertheless, ANSI C allows the alternate
  233.  
  234.                 #define NULL ((void *)0)
  235.  
  236.         definition for NULL.  Besides helping incorrect programs to work
  237.         (but only on machines with homogeneous pointers, thus
  238.         questionably valid assistance) this definition may catch
  239.         programs which use NULL incorrectly (e.g. when the ASCII  NUL
  240.         character was really intended; see question 1.8).
  241.  
  242.         References: ANSI Rationale Sec. 4.1.5 p. 74.
  243.  
  244. 1.6:    I use the preprocessor macro
  245.  
  246.                 #define Nullptr(type) (type *)0
  247.  
  248.         to help me build null pointers of the correct type.
  249.  
  250. A:      This trick, though popular in some circles, does not buy much.
  251.         It is not needed in assignments and comparisons; see question
  252.         1.2.  It does not even save keystrokes.  Its use suggests to the
  253.         reader that the author is shaky on the subject of null pointers,
  254.         and requires the reader to check the #definition of the macro,
  255.         its invocations, and _all_ other pointer usages much more
  256.         carefully.  See also question 8.1.
  257.  
  258. 1.7:    Is the abbreviated pointer comparison "if(p)" to test for non-
  259.         null pointers valid?  What if the internal representation for
  260.         null pointers is nonzero?
  261.  
  262. A:      When C requires the boolean value of an expression (in the if,
  263.         while, for, and do statements, and with the &&, ||, !, and ?:
  264.         operators), a false value is produced when the expression
  265.         compares equal to zero, and a true value otherwise.  That is,
  266.         whenever one writes
  267.  
  268.                 if(expr)
  269.  
  270.         where "expr" is any expression at all, the compiler essentially
  271.         acts as if it had been written as
  272.  
  273.                 if(expr != 0)
  274.  
  275.         Substituting the trivial pointer expression "p" for "expr," we
  276.         have
  277.  
  278.                 if(p)   is equivalent to                if(p != 0)
  279.  
  280.         and this is a comparison context, so the compiler can tell that
  281.         the (implicit) 0 is a null pointer, and use the correct value.
  282.         There is no trickery involved here; compilers do work this way,
  283.         and generate identical code for both statements.  The internal
  284.         representation of a pointer does _not_ matter.
  285.  
  286.         The boolean negation operator, !, can be described as follows:
  287.  
  288.                 !expr   is essentially equivalent to    expr?0:1
  289.  
  290.         It is left as an exercise for the reader to show that
  291.  
  292.                 if(!p)  is equivalent to                if(p == 0)
  293.  
  294.         "Abbreviations" such as if(p), though perfectly legal, are
  295.         considered by some to be bad style.
  296.  
  297.         See also question 8.2.
  298.  
  299.         References: K&R II Sec. A7.4.7 p. 204; H&S Sec. 5.3 p. 91; ANSI
  300.         Secs. 3.3.3.3, 3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, and
  301.         3.6.5 .
  302.  
  303. 1.8:    If "NULL" and "0" are equivalent, which should I use?
  304.  
  305. A:      Many programmers believe that "NULL" should be used in all
  306.         pointer contexts, as a reminder that the value is to be thought
  307.         of as a pointer.  Others feel that the confusion surrounding
  308.         "NULL" and "0" is only compounded by hiding "0" behind a
  309.         #definition, and prefer to use unadorned "0" instead.  There is
  310.         no one right answer.  C programmers must understand that "NULL"
  311.         and "0" are interchangeable and that an uncast "0" is perfectly
  312.         acceptable in initialization, assignment, and comparison
  313.         contexts.  Any usage of "NULL" (as opposed to "0") should be
  314.         considered a gentle reminder that a pointer is involved;
  315.         programmers should not depend on it (either for their own
  316.         understanding or the compiler's) for distinguishing pointer 0's
  317.         from integer 0's.
  318.  
  319.         NULL should _not_ be used when another kind of 0 is required,
  320.         even though it might work, because doing so sends the wrong
  321.         stylistic message.  (ANSI allows the #definition of NULL to be
  322.         (void *)0, which will not work in non-pointer contexts.)  In
  323.         particular, do not use NULL when the ASCII null character (NUL)
  324.         is desired.  Provide your own definition
  325.  
  326.                 #define NUL '\0'
  327.  
  328.         if you must.
  329.  
  330.         References: K&R II Sec. 5.4 p. 102.
  331.  
  332. 1.9:    But wouldn't it be better to use NULL (rather than 0) in case
  333.         the value of NULL changes, perhaps on a machine with nonzero
  334.         null pointers?
  335.  
  336. A:      No.  Although symbolic constants are often used in place of
  337.         numbers because the numbers might change, this is _not_ the
  338.         reason that NULL is used in place of 0.  Once again, the
  339.         language guarantees that source-code 0's (in pointer contexts)
  340.         generate null pointers.  NULL is used only as a stylistic
  341.         convention.
  342.  
  343. 1.10:   I'm confused.  NULL is guaranteed to be 0, but the null pointer
  344.         is not?
  345.  
  346. A:      When the term "null" or "NULL" is casually used, one of several
  347.         things may be meant:
  348.  
  349.         1.      The conceptual null pointer, the abstract language
  350.                 concept defined in question 1.1.  It is implemented
  351.                 with...
  352.  
  353.         2.      The internal (or run-time) representation of a null
  354.                 pointer, which may or may not be all-bits-0 and which
  355.                 may be different for different pointer types.  The
  356.                 actual values should be of concern only to compiler
  357.                 writers.  Authors of C programs never see them, since
  358.                 they use...
  359.  
  360.         3.      The source code syntax for null pointers, which is the
  361.                 single character "0".  It is often hidden behind...
  362.  
  363.         4.      The NULL macro, which is #defined to be "0" or
  364.                 "(void *)0".  Finally, as red herrings, we have...
  365.  
  366.         5.      The ASCII null character (NUL), which does have all bits
  367.                 zero, but has no relation to the null pointer except in
  368.                 name; and...
  369.  
  370.         6.      The "null string," which is another name for an empty
  371.                 string ("").  The term "null string" can be confusing in
  372.                 C (and should perhaps be avoided), because it involves a
  373.                 null ('\0') character, but not a null pointer, which
  374.                 brings us full circle...
  375.  
  376.         This article always uses the phrase "null pointer" (in lower
  377.         case) for sense 1, the character "0" for sense 3, and the
  378.         capitalized word "NULL" for sense 4.
  379.  
  380. 1.11:   Why is there so much confusion surrounding null pointers?  Why
  381.         do these questions come up so often?
  382.  
  383. A:      C programmers traditionally like to know more than they need to
  384.         about the underlying machine implementation.  The fact that null
  385.         pointers are represented both in source code, and internally to
  386.         most machines, as zero invites unwarranted assumptions.  The use
  387.         of a preprocessor macro (NULL) suggests that the value might
  388.         change later, or on some weird machine.  The construct
  389.         "if(p == 0)" is easily misread as calling for conversion of p to
  390.         an integral type, rather than 0 to a pointer type, before the
  391.         comparison.  Finally, the distinction between the several uses
  392.         of the term "null" (listed above) is often overlooked.
  393.  
  394.         One good way to wade out of the confusion is to imagine that C
  395.         had a keyword (perhaps "nil", like Pascal) with which null
  396.         pointers were requested.  The compiler could either turn "nil"
  397.         into the correct type of null pointer, when it could determine
  398.         the type from the source code, or complain when it could not.
  399.         Now, in fact, in C the keyword for a null pointer is not "nil"
  400.         but "0", which works almost as well, except that an uncast "0"
  401.         in a non-pointer context generates an integer zero instead of an
  402.         error message, and if that uncast 0 was supposed to be a null
  403.         pointer, the code may not work.
  404.  
  405. 1.12:   I'm still confused.  I just can't understand all this null
  406.         pointer stuff.
  407.  
  408. A:      Follow these two simple rules:
  409.  
  410.         1.      When you want to refer to a null pointer in source code,
  411.                 use "0" or "NULL".
  412.  
  413.         2.      If the usage of "0" or "NULL" is an argument in a
  414.                 function call, cast it to the pointer type expected by
  415.                 the function being called.
  416.  
  417.         The rest of the discussion has to do with other people's
  418.         misunderstandings, or with the internal representation of null
  419.         pointers (which you shouldn't need to know), or with ANSI C
  420.         refinements.  Understand questions 1.1, 1.2, and 1.3, and
  421.         consider 1.8 and 1.11, and you'll do fine.
  422.  
  423. 1.13:   Given all the confusion surrounding null pointers, wouldn't it
  424.         be easier simply to require them to be represented internally by
  425.         zeroes?
  426.  
  427. A:      If for no other reason, doing so would be ill-advised because it
  428.         would unnecessarily constrain implementations which would
  429.         otherwise naturally represent null pointers by special, nonzero
  430.         bit patterns, particularly when those values would trigger
  431.         automatic hardware traps for invalid accesses.
  432.  
  433.         Besides, what would this requirement really accomplish?  Proper
  434.         understanding of null pointers does not require knowledge of the
  435.         internal representation, whether zero or nonzero.  Assuming that
  436.         null pointers are internally zero does not make any code easier
  437.         to write (except for a certain ill-advised usage of calloc; see
  438.         question 3.11).  Known-zero internal pointers would not obviate
  439.         casts in function calls, because the _size_ of the pointer might
  440.         still be different from that of an int.  (If "nil" were used to
  441.         request null pointers rather than "0," as mentioned in question
  442.         1.11, the urge to assume an internal zero representation would
  443.         not even arise.)
  444.  
  445. 1.14:   Seriously, have any actual machines really used nonzero null
  446.         pointers, or different representations for pointers to different
  447.         types?
  448.  
  449. A:      The Prime 50 series used segment 07777, offset 0 for the null
  450.         pointer, at least for PL/I.  Later models used segment 0, offset
  451.         0 for null pointers in C, necessitating new instructions such as
  452.         TCNP (Test C Null Pointer), evidently as a sop to all the extant
  453.         poorly-written C code which made incorrect assumptions.  Older,
  454.         word-addressed Prime machines were also notorious for requiring
  455.         larger byte pointers (char *'s) than word pointers (int *'s).
  456.  
  457.         The Eclipse MV series from Data General has three
  458.         architecturally supported pointer formats (word, byte, and bit
  459.         pointers), two of which are used by C compilers: byte pointers
  460.         for char * and void *, and word pointers for everything else.
  461.  
  462.         Some Honeywell-Bull mainframes use the bit pattern 06000 for
  463.         (internal) null pointers.
  464.  
  465.         The CDC Cyber 180 Series has 48-bit pointers consisting of a
  466.         ring, segment, and offset.  Most users (in ring 11) have null
  467.         pointers of 0xB00000000000.
  468.  
  469.         The Symbolics Lisp Machine, a tagged architecture, does not even
  470.         have conventional numeric pointers; it uses the pair <NIL, 0>
  471.         (basically a nonexistent <object, offset> handle) as a C null
  472.         pointer.
  473.  
  474.         Depending on the "memory model" in use, 80*86 processors (PC's)
  475.         may use 16 bit data pointers and 32 bit function pointers, or
  476.         vice versa.
  477.  
  478. 1.15:   What does a run-time "null pointer assignment" error mean?  How
  479.         do I track it down?
  480.  
  481. A:      This message, which occurs only under MS-DOS (see, therefore,
  482.         section 16) means that you've written, via a null pointer, to
  483.         location zero.
  484.  
  485.         A debugger will usually let you set a data breakpoint on
  486.         location 0.  Alternately, you could write a bit of code to copy
  487.         20 or so bytes from location 0 into another buffer, and
  488.         periodically check that it hasn't changed.
  489.  
  490.  
  491. Section 2. Arrays and Pointers
  492.  
  493. 2.1:    I had the definition char a[6] in one source file, and in
  494.         another I declared extern char *a.  Why didn't it work?
  495.  
  496. A:      The declaration extern char *a simply does not match the actual
  497.         definition.  The type "pointer-to-type-T" is not the same as
  498.         "array-of-type-T."  Use extern char a[].
  499.  
  500.         References: CT&P Sec. 3.3 pp. 33-4, Sec. 4.5 pp. 64-5.
  501.  
  502. 2.2:    But I heard that char a[] was identical to char *a.
  503.  
  504. A:      Not at all.  (What you heard has to do with formal parameters to
  505.         functions; see question 2.4.)  Arrays are not pointers.  The
  506.         array declaration "char a[6];" requests that space for six
  507.         characters be set aside, to be known by the name "a."  That is,
  508.         there is a location named "a" at which six characters can sit.
  509.         The pointer declaration "char *p;" on the other hand, requests a
  510.         place which holds a pointer.  The pointer is to be known by the
  511.         name "p," and can point to any char (or contiguous array of
  512.         chars) anywhere.
  513.  
  514.         As usual, a picture is worth a thousand words.  The statements
  515.  
  516.                 char a[] = "hello";
  517.                 char *p = "world";
  518.  
  519.         would result in data structures which could be represented like
  520.         this:
  521.  
  522.                    +---+---+---+---+---+---+
  523.                 a: | h | e | l | l | o |\0 |
  524.                    +---+---+---+---+---+---+
  525.  
  526.                    +-----+     +---+---+---+---+---+---+
  527.                 p: |  *======> | w | o | r | l | d |\0 |
  528.                    +-----+     +---+---+---+---+---+---+
  529.  
  530.         It is important to realize that a reference like x[3] generates
  531.         different code depending on whether x is an array or a pointer.
  532.         Given the declarations above, when the compiler sees the
  533.         expression a[3], it emits code to start at the location "a,"
  534.         move three past it, and fetch the character there.  When it sees
  535.         the expression p[3], it emits code to start at the location "p,"
  536.         fetch the pointer value there, add three to the pointer, and
  537.         finally fetch the character pointed to.  In the example above,
  538.         both a[3] and p[3] happen to be the character 'l', but the
  539.         compiler gets there differently.  (See also question 17.14.)
  540.  
  541. 2.3:    So what is meant by the "equivalence of pointers and arrays" in
  542.         C?
  543.  
  544. A:      Much of the confusion surrounding pointers in C can be traced to
  545.         a misunderstanding of this statement.  Saying that arrays and
  546.         pointers are "equivalent" does not by any means imply that they
  547.         are interchangeable.
  548.  
  549.         "Equivalence" refers to the following key definition:
  550.  
  551.                 An lvalue [see question 2.5] of type array-of-T
  552.                 which appears in an expression decays (with
  553.                 three exceptions) into a pointer to its first
  554.                 element; the type of the resultant pointer is
  555.                 pointer-to-T.
  556.  
  557.         (The exceptions are when the array is the operand of a sizeof or
  558.         & operator, or is a literal string initializer for a character
  559.         array.)
  560.  
  561.         As a consequence of this definition, there is no apparent
  562.         difference in the behavior of the "array subscripting" operator
  563.         [] as it applies to arrays and pointers.  In an expression of
  564.         the form a[i], the array reference "a" decays into a pointer,
  565.         following the rule above, and is then subscripted just as would
  566.         be a pointer variable in the expression p[i] (although the
  567.         eventual memory accesses will be different, as explained in
  568.         question 2.2).  In either case, the expression x[i] (where x is
  569.         an array or a pointer) is, by definition, exactly equivalent to
  570.         *((x)+(i)).
  571.  
  572.         References: K&R I Sec. 5.3 pp. 93-6; K&R II Sec. 5.3 p. 99; H&S
  573.         Sec. 5.4.1 p. 93; ANSI Sec. 3.2.2.1, Sec. 3.3.2.1, Sec. 3.3.6 .
  574.  
  575. 2.4:    Then why are array and pointer declarations interchangeable as
  576.         function formal parameters?
  577.  
  578. A:      Since arrays decay immediately into pointers, an array is never
  579.         actually passed to a function.  As a convenience, any parameter
  580.         declarations which "look like" arrays, e.g.
  581.  
  582.                 f(a)
  583.                 char a[];
  584.  
  585.         are treated by the compiler as if they were pointers, since that
  586.         is what the function will receive if an array is passed:
  587.  
  588.                 f(a)
  589.                 char *a;
  590.  
  591.         This conversion holds only within function formal parameter
  592.         declarations, nowhere else.  If this conversion bothers you,
  593.         avoid it; many people have concluded that the confusion it
  594.         causes outweighs the small advantage of having the declaration
  595.         "look like" the call and/or the uses within the function.
  596.  
  597.         References: K&R I Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R II
  598.         Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; H&S
  599.         Sec. 5.4.3 p. 96; ANSI Sec. 3.5.4.3, Sec. 3.7.1, CT&P Sec. 3.3
  600.         pp. 33-4.
  601.  
  602. 2.5:    How can an array be an lvalue, if you can't assign to it?
  603.  
  604. A:      The ANSI C Standard defines a "modifiable lvalue," which an
  605.         array is not.
  606.  
  607.         References: ANSI Sec. 3.2.2.1 p. 37.
  608.  
  609. 2.6:    Why doesn't sizeof properly report the size of an array which is
  610.         a parameter to a function?
  611.  
  612. A:      The sizeof operator reports the size of the pointer parameter
  613.         which the function actually receives (see question 2.4).
  614.  
  615. 2.7:    Someone explained to me that arrays were really just constant
  616.         pointers.
  617.  
  618. A:      This is a bit of an oversimplification.  An array name is
  619.         "constant" in that it cannot be assigned to, but an array is
  620.         _not_ a pointer, as the discussion and pictures in question 2.2
  621.         should make clear.
  622.  
  623. 2.8:    Practically speaking, what is the difference between arrays and
  624.         pointers?
  625.  
  626. A:      Arrays automatically allocate space, but can't be relocated or
  627.         resized.  Pointers must be explicitly assigned to point to
  628.         allocated space (perhaps using malloc), but can be reassigned
  629.         (i.e. pointed at different objects) at will, and have many other
  630.         uses besides serving as the base of blocks of memory.
  631.  
  632.         Due to the "equivalence of arrays and pointers" (see question
  633.         2.3), arrays and pointers often seem interchangeable, and in
  634.         particular a pointer to a block of memory assigned by malloc is
  635.         frequently treated (and can be referenced using [] exactly) as
  636.         if it were a true array (see also question 2.13).
  637.  
  638. 2.9:    I came across some "joke" code containing the "expression"
  639.         5["abcdef"] .  How can this be legal C?
  640.  
  641. A:      Yes, Virginia, array subscripting is commutative in C.  This
  642.         curious fact follows from the pointer definition of array
  643.         subscripting, namely that a[e] is exactly equivalent to
  644.         *((a)+(e)), for _any_ expression e and primary expression a, as
  645.         long as one of them is a pointer expression and one is integral.
  646.         This unsuspected commutativity is often mentioned in C texts as
  647.         if it were something to be proud of, but it finds no useful
  648.         application outside of the Obfuscated C Contest (see question
  649.         17.9).
  650.  
  651.         References: ANSI Rationale Sec. 3.3.2.1 p. 41.
  652.  
  653. 2.10:   My compiler complained when I passed a two-dimensional array to
  654.         a routine expecting a pointer to a pointer.
  655.  
  656. A:      The rule by which arrays decay into pointers is not applied
  657.         recursively.  An array of arrays (i.e. a two-dimensional array
  658.         in C) decays into a pointer to an array, not a pointer to a
  659.         pointer.  Pointers to arrays can be confusing, and must be
  660.         treated carefully.  (The confusion is heightened by the
  661.         existence of incorrect compilers, including some versions of pcc
  662.         and pcc-derived lint's, which improperly accept assignments of
  663.         multi-dimensional arrays to multi-level pointers.)  If you are
  664.         passing a two-dimensional array to a function:
  665.  
  666.                 int array[NROWS][NCOLUMNS];
  667.                 f(array);
  668.  
  669.         the function's declaration should match:
  670.  
  671.                 f(int a[][NCOLUMNS]) {...}
  672.         or
  673.                 f(int (*ap)[NCOLUMNS]) {...}    /* ap is a pointer to an array
  674. */
  675.  
  676.         In the first declaration, the compiler performs the usual
  677.         implicit parameter rewriting of "array of array" to "pointer to
  678.         array;" in the second form the pointer declaration is explicit.
  679.         Since the called function does not allocate space for the array,
  680.         it does not need to know the overall size, so the number of
  681.         "rows," NROWS, can be omitted.  The "shape" of the array is
  682.         still important, so the "column" dimension NCOLUMNS (and, for 3-
  683.         or more dimensional arrays, the intervening ones) must be
  684.         included.
  685.  
  686.         If a function is already declared as accepting a pointer to a
  687.         pointer, it is probably incorrect to pass a two-dimensional
  688.         array directly to it.
  689.  
  690.         References: K&R I Sec. 5.10 p. 110; K&R II Sec. 5.9 p. 113.
  691.  
  692. 2.11:   How do I write functions which accept 2-dimensional arrays when
  693.         the "width" is not known at compile time?
  694.  
  695. A:      It's not easy.  One way is to pass in pointer to the [0][0]
  696.         element, along with the two dimensions, and simulate array
  697.         subscripting "by hand:"
  698.  
  699.                 f2(aryp, m, n)
  700.                 int *aryp;
  701.                 int m, n;
  702.                 { ... ary[i][j] is really aryp[i * n + j] ... }
  703.  
  704.         This function could be called with the array from question 2.10
  705.         as
  706.  
  707.                 f2(&array[0][0], NROWS, NCOLUMNS);
  708.  
  709.         See also question 2.14.
  710.  
  711. 2.12:   How do I declare a pointer to an array?
  712.  
  713. A:      Usually, you don't want to.  When people speak casually of a
  714.         pointer to an array, they usually mean a pointer to its first
  715.         element.
  716.  
  717.         Instead of a pointer to an array, consider using a pointer to
  718.         one of the array's elements instead.  Arrays of type T decay
  719.         into pointers to type T (see question 2.3), which is convenient;
  720.         subscripting or incrementing the resultant pointer accesses the
  721.         individual members of the array.  True pointers to arrays, when
  722.         subscripted or incremented, step over entire arrays, and are
  723.         generally only useful when operating on arrays of arrays, if at
  724.         all.  (See question 2.10 above.)
  725.  
  726.         If you really need to declare a pointer to an entire array, use
  727.         something like "int (*ap)[N];" where N is the size of the array.
  728.         (See also question 10.4.)  If the size of the array is unknown,
  729.         N can be omitted, but the resulting type, "pointer to array of
  730.         unknown size," is useless.
  731.  
  732. 2.13:   How can I dynamically allocate a multidimensional array?
  733.  
  734. A:      It is usually best to allocate an array of pointers, and then
  735.         initialize each pointer to a dynamically-allocated "row."  Here
  736.         is a two-dimensional example:
  737.  
  738.                 int **array1 = (int **)malloc(nrows * sizeof(int *));
  739.                 for(i = 0; i < nrows; i++)
  740.                         array1[i] = (int *)malloc(ncolumns * sizeof(int));
  741.  
  742.         (In "real" code, of course, malloc would be declared correctly,
  743.         and each return value checked.)
  744.  
  745.         You can keep the array's contents contiguous, while making later
  746.         reallocation of individual rows difficult, with a bit of
  747.         explicit pointer arithmetic:
  748.  
  749.                 int **array2 = (int **)malloc(nrows * sizeof(int *));
  750.                 array2[0] = (int *)malloc(nrows * ncolumns * sizeof(int));
  751.                 for(i = 1; i < nrows; i++)
  752.                         array2[i] = array2[0] + i * ncolumns;
  753.  
  754.         In either case, the elements of the dynamic array can be
  755.         accessed with normal-looking array subscripts: array[i][j].
  756.  
  757.         If the double indirection implied by the above schemes is for
  758.         some reason unacceptable, you can simulate a two-dimensional
  759.         array with a single, dynamically-allocated one-dimensional
  760.         array:
  761.  
  762.                 int *array3 = (int *)malloc(nrows * ncolumns * sizeof(int));
  763.  
  764.         However, you must now perform subscript calculations manually,
  765.         accessing the i,jth element with array3[i * ncolumns + j].  (A
  766.         macro can hide the explicit calculation, but invoking it then
  767.         requires parentheses and commas which don't look exactly like
  768.         multidimensional array subscripts.)
  769.  
  770.         Finally, you can use pointers-to-arrays:
  771.  
  772.                 int (*array4)[NCOLUMNS] =
  773.                         (int (*)[NCOLUMNS])malloc(nrows * sizeof(*array4));
  774.  
  775.         , but the syntax gets horrific and all but one dimension must be
  776.         known at compile time.
  777.  
  778.         With all of these techniques, you may of course need to remember
  779.         to free the arrays (which may take several steps; see question
  780.         3.8) when they are no longer needed, and you cannot necessarily
  781.         intermix the dynamically-allocated arrays with conventional,
  782.         statically-allocated ones (see question 2.14 below, and also
  783.         question 2.10).
  784.  
  785. 2.14:   How can I use statically- and dynamically-allocated
  786.         multidimensional arrays interchangeably when passing them to
  787.         functions?
  788.  
  789. A:      There is no single perfect method.  Given the array and f() as
  790.         declared in question 2.10, f2() as declared in question 2.11,
  791.         array1, array2, array3, and array4 as declared in 2.13, and a
  792.         function f3() declared as:
  793.  
  794.                 f3(pp, m, n)
  795.                 int **pp;
  796.                 int m, n;
  797.  
  798.         ; the following calls would be legal, and work as expected:
  799.  
  800.                 f(array, NROWS, NCOLUMNS);
  801.                 f(array4, nrows, NCOLUMNS);
  802.                 f2(&array[0][0], NROWS, NCOLUMNS);
  803.                 f2(*array2, nrows, ncolumns);
  804.                 f2(array3, nrows, ncolumns);
  805.                 f2(*array4, nrows, NCOLUMNS);
  806.                 f3(array1, nrows, ncolumns);
  807.                 f3(array2, nrows, ncolumns);
  808.  
  809.         The following two calls would probably work, but involve
  810.         questionable casts, and work only if the dynamic ncolumns
  811.         matches the static NCOLUMNS:
  812.  
  813.                 f((int (*)[NCOLUMNS])(*array2), nrows, ncolumns);
  814.                 f((int (*)[NCOLUMNS])array3, nrows, ncolumns);
  815.  
  816.         If you can understand why all of the above calls work and are
  817.         written as they are, and if you understand why the combinations
  818.         that are not listed would not work, then you have a _very_ good
  819.         understanding of arrays and pointers (and several other areas)
  820.         in C.
  821.  
  822. 2.15:   Here's a neat trick: if I write
  823.  
  824.                 int realarray[10];
  825.                 int *array = &realarray[-1];
  826.  
  827.         I can treat "array" as if it were a 1-based array.
  828.  
  829. A:      Although this technique is attractive (and is used in the book
  830.         Numerical Recipes in C), it does not conform to the C standards.
  831.         Pointer arithmetic is defined only as long as the pointer points
  832.         within the same allocated block of memory, or to the imaginary
  833.         "terminating" element one past it; otherwise, the behavior is
  834.         undefined, _even if the pointer is not dereferenced_.  The code
  835.         above could fail if, while subtracting the offset, an illegal
  836.         address were generated (perhaps because the address tried to
  837.         "wrap around" past the beginning of some memory segment).
  838.  
  839.         References: ANSI Sec. 3.3.6 p. 48, Rationale Sec. 3.2.2.3 p. 38;
  840.         K&R II Sec. 5.3 p. 100, Sec. 5.4 pp. 102-3, Sec. A7.7 pp. 205-6.
  841.  
  842. 2.16:   I passed a pointer to a function which initialized it:
  843.  
  844.                 main()
  845.                 {
  846.                         int *ip;
  847.                         f(ip);
  848.                         return 0;
  849.                 }
  850.  
  851.                 void f(ip)
  852.                 int *ip;
  853.                 {
  854.                         static int dummy;
  855.                         ip = &dummy;
  856.                         *ip = 5;
  857.                 }
  858.  
  859.         , but the pointer in the caller was unchanged.
  860.  
  861. A:      Did the function try to initialize the pointer itself, or just
  862.         what it pointed to?  Remember that arguments in C are passed by
  863.         value.  The called function altered only the passed copy of the
  864.         pointer.  You'll want to pass the address of the pointer (the
  865.         function will end up accepting a pointer-to-a-pointer).
  866.  
  867. 2.17:   I have a char * pointer that happens to point to some ints, and
  868.         I want to step it over them.  Why doesn't
  869.  
  870.                 ((int *)p)++;
  871.  
  872.         work?
  873.  
  874. A:      In C, a cast operator does not mean "pretend these bits have a
  875.         different type, and treat them accordingly;" it is a conversion
  876.         operator, and by definition it yields an rvalue, which cannot be
  877.         assigned to, or incremented with ++.  (It is an anomaly in pcc-
  878.         derived compilers, and an extension in gcc, that expressions
  879.         such as the above are ever accepted.)  Say what you mean: use
  880.  
  881.                 p = (char *)((int *)p + 1);
  882.  
  883.         , or simply
  884.  
  885.                 p += sizeof(int);
  886.  
  887.         References: ANSI Sec. 3.3.4, Rationale Sec. 3.3.2.4 p. 43.
  888.  
  889.  
  890. Section 3. Memory Allocation
  891.  
  892. 3.1:    Why doesn't this fragment work?
  893.  
  894.                 char *answer;
  895.                 printf("Type something:\n");
  896.                 gets(answer);
  897.                 printf("You typed \"%s\"\n", answer);
  898.  
  899. A:      The pointer variable "answer," which is handed to the gets
  900.         function as the location into which the response should be
  901.         stored, has not been set to point to any valid storage.  That
  902.         is, we cannot say where the pointer "answer" points.  (Since
  903.         local variables are not initialized, and typically contain
  904.         garbage, it is not even guaranteed that "answer" starts out as a
  905.         null pointer.  See question 17.1.)
  906.  
  907.         The simplest way to correct the question-asking program is to
  908.         use a local array, instead of a pointer, and let the compiler
  909.         worry about allocation:
  910.  
  911.                 #include <string.h>
  912.  
  913.                 char answer[100], *p;
  914.                 printf("Type something:\n");
  915.                 fgets(answer, 100, stdin);
  916.                 if((p = strchr(answer, '\n')) != NULL)
  917.                         *p = '\0';
  918.                 printf("You typed \"%s\"\n", answer);
  919.  
  920.         Note that this example also uses fgets instead of gets (always a
  921.         good idea), so that the size of the array can be specified, so
  922.         that fgets will not overwrite the end of the array if the user
  923.         types an overly-long line.  (Unfortunately for this example,
  924.         fgets does not automatically delete the trailing \n, as gets
  925.         would.)  It would also be possible to use malloc to allocate the
  926.         answer buffer, and/or to parameterize its size
  927.         (#define ANSWERSIZE 100).
  928.  
  929. 3.2:    I can't get strcat to work.  I tried
  930.  
  931.                 char *s1 = "Hello, ";
  932.                 char *s2 = "world!";
  933.                 char *s3 = strcat(s1, s2);
  934.  
  935.         but I got strange results.
  936.  
  937. A:      Again, the problem is that space for the concatenated result is
  938.         not properly allocated.  C does not provide an automatically-
  939.         managed string type.  C compilers only allocate memory for
  940.         objects explicitly mentioned in the source code (in the case of
  941.         "strings," this includes character arrays and string literals).
  942.         The programmer must arrange (explicitly) for sufficient space
  943.         for the results of run-time operations such as string
  944.         concatenation, typically by declaring arrays, or by calling
  945.         malloc.
  946.  
  947.         strcat performs no allocation; the second string is appended to
  948.         the first one, in place.  Therefore, one fix would be to declare
  949.         the first string as an array with sufficient space:
  950.  
  951.                 char s1[20] = "Hello, ";
  952.  
  953.         Since strcat returns the value of its first argument (s1, in
  954.         this case), the s3 variable is superfluous.
  955.  
  956.         References: CT&P Sec. 3.2 p. 32.
  957.  
  958. 3.3:    But the man page for strcat says that it takes two char *'s as
  959.         arguments.  How am I supposed to know to allocate things?
  960.  
  961. A:      In general, when using pointers you _always_ have to consider
  962.         memory allocation, at least to make sure that the compiler is
  963.         doing it for you.  If a library routine's documentation does not
  964.         explicitly mention allocation, it is usually the caller's
  965.         problem.
  966.  
  967.         The Synopsis section at the top of a Unix-style man page can be
  968.         misleading.  The code fragments presented there are closer to
  969.         the function definition used by the call's implementor than the
  970.         invocation used by the caller.  In particular, many routines
  971.         which accept pointers (e.g. to structs or strings), are usually
  972.         called with the address of some object (a struct, or an array --
  973.         see questions 2.3 and 2.4.)  Another common example is stat().
  974.  
  975. 3.4:    I have a function that is supposed to return a string, but when
  976.         it returns to its caller, the returned string is garbage.
  977.  
  978. A:      Make sure that the memory to which the function returns a
  979.         pointer is correctly allocated.  The returned pointer should be
  980.         to a statically-allocated buffer, or to a buffer passed in by
  981.         the caller, but _not_ to a local array.  See also question 17.3.
  982.  
  983. 3.5:    You can't use dynamically-allocated memory after you free it,
  984.         can you?
  985.  
  986. A:      No.  Some early man pages for malloc stated that the contents of
  987.         freed memory was "left undisturbed;" this ill-advised guarantee
  988.         was never universal and is not required by ANSI.
  989.  
  990.         Few programmers would use the contents of freed memory
  991.         deliberately, but it is easy to do so accidentally.  Consider
  992.         the following (correct) code for freeing a singly-linked list:
  993.  
  994.                 struct list *listp, *nextp;
  995.                 for(listp = base; listp != NULL; listp = nextp) {
  996.                         nextp = listp->next;
  997.                         free((char *)listp);
  998.                 }
  999.  
  1000.         and notice what would happen if the more-obvious loop iteration
  1001.         expression listp = listp->next were used, without the temporary
  1002.         nextp pointer.
  1003.  
  1004.         References: ANSI Rationale Sec. 4.10.3.2 p. 102; CT&P Sec. 7.10
  1005.         p. 95.
  1006.  
  1007. 3.6:    How does free() know how many bytes to free?
  1008.  
  1009. A:      The malloc/free package remembers the size of each block it
  1010.         allocates and returns, so it is not necessary to remind it of
  1011.         the size when freeing.
  1012.  
  1013. 3.7:    So can I query the malloc package to find out how big an
  1014.         allocated block is?
  1015.  
  1016. A:      Not portably.
  1017.  
  1018. 3.8:    I'm allocating structures which contain pointers to other
  1019.         dynamically-allocated objects.  When I free a structure, do I
  1020.         have to free each subsidiary pointer first?
  1021.  
  1022. A:      Yes.  In general, you must arrange that each pointer returned
  1023.         from malloc be individually passed to free, exactly once (if it
  1024.         is freed at all).
  1025.  
  1026. 3.9:    I have a program which mallocs but then frees a lot of memory,
  1027.         but memory usage (as reported by ps) doesn't seem to go back
  1028.         down.
  1029.  
  1030. A:      Most implementations of malloc/free do not return freed memory
  1031.         to the operating system (if there is one), but merely make it
  1032.         available for future malloc calls.
  1033.  
  1034. 3.10:   Is it legal to pass a null pointer as the first argument to
  1035.         realloc()?  Why would you want to?
  1036.  
  1037. A:      ANSI C sanctions this usage (and the related realloc(..., 0),
  1038.         which frees), but several earlier implementations do not support
  1039.         it, so it is not widely portable.  Passing an initially-null
  1040.         pointer to realloc can make it easier to write a self-starting
  1041.         incremental allocation algorithm.
  1042.  
  1043.         References: ANSI Sec. 4.10.3.4 .
  1044.  
  1045. 3.11:   What is the difference between calloc and malloc?  Is it safe to
  1046.         use calloc's zero-fill guarantee for pointer and floating-point
  1047.         values?  Does free work on memory allocated with calloc, or do
  1048.         you need a cfree?
  1049.  
  1050. A:      calloc(m, n) is essentially equivalent to
  1051.  
  1052.                 p = malloc(m * n);
  1053.                 memset(p, 0, m * n);
  1054.  
  1055.         The zero fill is all-bits-zero, and does not therefore guarantee
  1056.         useful zero values for pointers (see section 1 of this list) or
  1057.         floating-point values.  free can (and should) be used to free
  1058.         the memory allocated by calloc.
  1059.  
  1060.         References: ANSI Secs. 4.10.3 to 4.10.3.2 .
  1061.  
  1062. 3.12:   What is alloca and why is its use discouraged?
  1063.  
  1064. A:      alloca allocates memory which is automatically freed when the
  1065.         function which called alloca returns.  That is, memory allocated
  1066.         with alloca is local to a particular function's "stack frame" or
  1067.         context.
  1068.  
  1069.         alloca cannot be written portably, and is difficult to implement
  1070.         on machines without a stack.  Its use is problematical (and the
  1071.         obvious implementation on a stack-based machine fails) when its
  1072.         return value is passed directly to another function, as in
  1073.         fgets(alloca(100), 100, stdin).
  1074.  
  1075.         For these reasons, alloca cannot be used in programs which must
  1076.         be widely portable, no matter how useful it might be.
  1077.  
  1078.         References: ANSI Rationale Sec. 4.10.3 p. 102.
  1079.  
  1080.  
  1081. Section 4. Expressions
  1082.  
  1083. 4.1:    Why doesn't this code:
  1084.  
  1085.                 a[i] = i++;
  1086.  
  1087.         work?
  1088.  
  1089. A:      The subexpression i++ causes a side effect -- it modifies i's
  1090.         value -- which leads to undefined behavior if i is also
  1091.         referenced elsewhere in the same expression.
  1092.  
  1093.         References: ANSI Sec. 3.3 p. 39.
  1094.  
  1095. 4.2:    Under my compiler, the code
  1096.  
  1097.                 int i = 7;
  1098.                 printf("%d\n", i++ * i++);
  1099.  
  1100.         prints 49.  Regardless of the order of evaluation, shouldn't it
  1101.         print 56?
  1102.  
  1103. A:      Although the postincrement and postdecrement operators ++ and --
  1104.         perform the operations after yielding the former value, the
  1105.         implication of "after" is often misunderstood.  It is _not_
  1106.         guaranteed that the operation is performed immediately after
  1107.         giving up the previous value and before any other part of the
  1108.         expression is evaluated.  It is merely guaranteed that the
  1109.         update will be performed sometime before the expression is
  1110.         considered "finished" (before the next "sequence point," in ANSI
  1111.         C's terminology).  In the example, the compiler chose to
  1112.         multiply the previous value by itself and to perform both
  1113.         increments afterwards.
  1114.  
  1115.         The behavior of code which contains multiple, ambiguous side
  1116.         effects has always been undefined.  Don't even try to find out
  1117.         how your compiler implements such things (contrary to the ill-
  1118.         advised exercises in many C textbooks); as K&R wisely point out,
  1119.         "if you don't know _how_ they are done on various machines, that
  1120.         innocence may help to protect you."
  1121.  
  1122.         References: K&R I Sec. 2.12 p. 50; K&R II Sec. 2.12 p. 54; ANSI
  1123.         Sec. 3.3 p. 39; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp. 120-1.
  1124.         (Ignore H&S Sec. 7.12 pp. 190-1, which is obsolete.)
  1125.  
  1126. 4.3:    But what about the &&, ||, and comma operators?
  1127.         I see code like "if((c = getchar()) == EOF || c == '\n')" ...
  1128.  
  1129. A:      There is a special exception for those operators, (as well as
  1130.         ?: ); each of them does imply a sequence point (i.e. left-to-
  1131.         right evaluation is guaranteed).  Any book on C should make this
  1132.         clear.
  1133.  
  1134.         References: K&R I Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1;
  1135.         K&R II Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ANSI
  1136.         Secs. 3.3.13 p. 52, 3.3.14 p. 52, 3.3.15 p. 53, 3.3.17 p. 55,
  1137.         CT&P Sec. 3.7 pp. 46-7.
  1138.  
  1139. 4.4:    If I'm not using the value of the expression, should I use i++
  1140.         or ++i to increment a variable?
  1141.  
  1142. A:      Since the two forms differ only in the value yielded, they are
  1143.         entirely equivalent when only their side effect is needed.  Some
  1144.         people will tell you that in the old days one form was preferred
  1145.         over the other because it utilized a PDP-11 autoincrement
  1146.         addressing mode, but those people are confused.
  1147.  
  1148. 4.5:    Why doesn't the code
  1149.  
  1150.                 int a = 1000, b = 1000;
  1151.                 long int c = a * b;
  1152.  
  1153.         work?
  1154.  
  1155. A:      Under C's integral promotion rules, the multiplication is
  1156.         carried out using int arithmetic, and the result may overflow
  1157.         and/or be truncated before being assigned to the long int left-
  1158.         hand-side.  Use an explicit cast to force long arithmetic:
  1159.  
  1160.                 long int c = (long int)a * b;
  1161.  
  1162.  
  1163. Section 5. ANSI C
  1164.  
  1165. 5.1:    What is the "ANSI C Standard?"
  1166.  
  1167. A:      In 1983, the American National Standards Institute commissioned
  1168.         a committee, X3J11, to standardize the C language.  After a
  1169.         long, arduous process, including several widespread public
  1170.         reviews, the committee's work was finally ratified as an
  1171.         American National Standard, X3.159-1989, on December 14, 1989,
  1172.         and published in the spring of 1990.  For the most part, ANSI C
  1173.         standardizes existing practice, with a few additions from C++
  1174.         (most notably function prototypes) and support for multinational
  1175.         character sets (including the much-lambasted trigraph
  1176.         sequences).  The ANSI C standard also formalizes the C run-time
  1177.         library support routines.
  1178.  
  1179.         The published Standard includes a "Rationale," which explains
  1180.         many of its decisions, and discusses a number of subtle points,
  1181.         including several of those covered here.  (The Rationale is "not
  1182.         part of ANSI Standard X3.159-1989, but is included for
  1183.         information only.")
  1184.  
  1185.         The Standard has been adopted as an international standard,
  1186.         ISO/IEC 9899:1990, although the sections are numbered
  1187.         differently (briefly, ANSI sections 2 through 4 correspond
  1188.         roughly to ISO sections 5 through 7), and the Rationale is
  1189.         currently not included.
  1190.  
  1191. 5.2:    How can I get a copy of the Standard?
  1192.  
  1193. A:      ANSI X3.159 has been officially superseded by ISO 9899.
  1194.         Copies are available from
  1195.  
  1196.                 American National Standards Institute
  1197.                 11 W. 42nd St., 13th floor
  1198.                 New York, NY  10036  USA
  1199.                 (+1) 212 642 4900
  1200.  
  1201.         or
  1202.  
  1203.                 Global Engineering Documents
  1204.                 2805 McGaw Avenue
  1205.                 Irvine, CA  92714  USA
  1206.                 (+1) 714 261 1455
  1207.                 (800) 854 7179  (U.S. & Canada)
  1208.  
  1209.         The cost is $130.00 from ANSI or $162.50 from Global.
  1210.         Copies of the original X3.159 (including the Rationale) are
  1211.         still available at $205.00 from ANSI or $200.50 from Global.
  1212.         (Editorial comment: yes, these prices are outrageous.)
  1213.  
  1214.         Note that ANSI derives revenues to support its operations from
  1215.         the sale of printed standards, so electronic copies are _not_
  1216.         available.
  1217.  
  1218.         The Rationale, by itself, has been printed by Silicon Press,
  1219.         ISBN 0-929306-07-4.
  1220.  
  1221. 5.3:    Does anyone have a tool for converting old-style C programs to
  1222.         ANSI C, or vice versa, or for automatically generating
  1223.         prototypes?
  1224.  
  1225. A:      First, are you sure you really need to convert lots of old code
  1226.         to ANSI C?  The old-style function syntax is still acceptable.
  1227.  
  1228.         Two programs, protoize and unprotoize, convert back and forth
  1229.         between prototyped and "old style" function definitions and
  1230.         declarations.  (These programs do _not_ handle full-blown
  1231.         translation between "Classic" C and ANSI C.)  These programs
  1232.         exist as patches to the FSF GNU C compiler, gcc.  Look for the
  1233.         file protoize-1.39.0.5.Z in pub/gnu at prep.ai.mit.edu
  1234.         (18.71.0.38), or at several other FSF archive sites.
  1235.  
  1236.         The unproto program (/pub/unix/unproto4.shar.Z on
  1237.         ftp.win.tue.nl) is a filter which sits between the preprocessor
  1238.         and the next compiler pass, converting most of ANSI C to
  1239.         traditional C on-the-fly.
  1240.  
  1241.         The GNU GhostScript package comes with a little program called
  1242.         ansi2knr.
  1243.  
  1244.         Several prototype generators exist, many as modifications to
  1245.         lint.  Version 3 of CPROTO was posted to comp.sources.misc in
  1246.         March, 1992.  (See also question 17.8.)
  1247.  
  1248. 5.4:    I'm trying to use the ANSI "stringizing" preprocessing operator
  1249.         # to insert the value of a symbolic constant into a message, but
  1250.         it keeps stringizing the macro's name rather than its value.
  1251.  
  1252. A:      You must use something like the following two-step procedure to
  1253.         force the macro to be expanded as well as stringized:
  1254.  
  1255.                 #define str(x) #x
  1256.                 #define xstr(x) str(x)
  1257.                 #define OP plus
  1258.                 char *opname = xstr(OP);
  1259.  
  1260.         This sets opname to "plus" rather than "OP".
  1261.  
  1262.         An equivalent circumlocution is necessary with the token-pasting
  1263.         operator ## when the values (rather than the names) of two
  1264.         macros are to be concatenated.
  1265.  
  1266.         References: ANSI Sec. 3.8.3.2, Sec. 3.8.3.5 example p. 93.
  1267.  
  1268. 5.5:    What's the difference between "char const *p" and
  1269.         "char * const p"?
  1270.  
  1271. A:      "char const *p" is a pointer to a constant character (you can't
  1272.         change the character); "char * const p" is a constant pointer to
  1273.         a (variable) character (i.e. you can't change the pointer).
  1274.         (Read these "inside out" to understand them.  See question
  1275.         10.4.)
  1276.  
  1277.         References: ANSI Sec. 3.5.4.1 .
  1278.  
  1279. 5.6:    Why can't I pass a char ** to a function which expects a
  1280.         const char **?
  1281.  
  1282. A:      You can use a pointer-to-T (for any type T) where a pointer-to-
  1283.         const-T is expected, but the rule (an explicit exception) which
  1284.         permits slight mismatches in qualified pointer types is not
  1285.         applied recursively, but only at the top level.
  1286.  
  1287.         You must use explicit casts (e.g. (const char **) in this case)
  1288.         when assigning (or passing) pointers which have qualifier
  1289.         mismatches at other than the first level of indirection.
  1290.  
  1291.         References: ANSI Sec. 3.1.2.6 p. 26, Sec. 3.3.16.1 p. 54,
  1292.         Sec. 3.5.3 p. 65.
  1293.  
  1294. 5.7:    My ANSI compiler complains about a mismatch when it sees
  1295.  
  1296.                 extern int func(float);
  1297.  
  1298.                 int func(x)
  1299.                 float x;
  1300.                 {...
  1301.  
  1302. A:      You have mixed the new-style prototype declaration
  1303.         "extern int func(float);" with the old-style definition
  1304.         "int func(x) float x;".  Old C (and ANSI C, in the absence of
  1305.         prototypes, and in variable-length argument lists) "widens"
  1306.         certain arguments when they are passed to functions.  Type float
  1307.         is promoted to double, and characters and short integers are
  1308.         promoted to integers.  (The values are automatically converted
  1309.         back to the corresponding narrower types within the body of the
  1310.         called function, if they are declared that way there.)
  1311.  
  1312.         The problem can be fixed either by using new-style syntax
  1313.         consistently in the definition:
  1314.  
  1315.                 int func(float x) { ... }
  1316.  
  1317.         or by changing the new-style prototype declaration to match the
  1318.         old-style definition:
  1319.  
  1320.                 extern int func(double);
  1321.  
  1322.         (In this case, it would be clearest to change the old-style
  1323.         definition to use double as well, as long as the address of that
  1324.         parameter is not taken.)
  1325.  
  1326.         It may also be safer to avoid "narrow" (char, short int, and
  1327.         float) function arguments and return types.
  1328.  
  1329.         References: ANSI Sec. 3.3.2.2 .
  1330.  
  1331. 5.8:    Why does the declaration
  1332.  
  1333.                 extern f(struct x {int s;} *p);
  1334.  
  1335.         give me an obscure warning message about "struct x introduced in
  1336.         prototype scope"?
  1337.  
  1338. A:      In a quirk of C's normal block scoping rules, a struct declared
  1339.         only within a prototype cannot be compatible with other structs
  1340.         declared in the same source file, nor can the struct tag be used
  1341.         later as you'd expect (it goes out of scope at the end of the
  1342.         prototype).
  1343.  
  1344.         To resolve the problem, precede the prototype with the vacuous-
  1345.         looking declaration
  1346.  
  1347.                 struct x;
  1348.  
  1349.         , which will reserve a place at file scope for struct x's
  1350.         definition, which will be completed by the struct declaration
  1351.         within the prototype.
  1352.  
  1353.         References: ANSI Sec. 3.1.2.1 p. 21, Sec. 3.1.2.6 p. 26,
  1354.         Sec. 3.5.2.3 p. 63.
  1355.  
  1356. 5.9:    I'm getting strange syntax errors inside code which I've
  1357.         #ifdeffed out.
  1358.  
  1359. A:      Under ANSI C, the text inside a "turned off" #if, #ifdef, or
  1360.         #ifndef must still consist of "valid preprocessing tokens."
  1361.         This means that there must be no unterminated comments or quotes
  1362.         (note particularly that an apostrophe within a contracted word
  1363.         could look like the beginning of a character constant), and no
  1364.         newlines inside quotes.  Therefore, natural-language comments
  1365.         and pseudocode should always be written between the "official"
  1366.         comment delimiters /* and */.  (But see also question 17.10, and
  1367.         6.7.)
  1368.  
  1369.         References: ANSI Sec. 2.1.1.2 p. 6, Sec. 3.1 p. 19 line 37.
  1370.  
  1371. 5.10:   Can I declare main as void, to shut off these annoying "main
  1372.         returns no value" messages?  (I'm calling exit(), so main
  1373.         doesn't return.)
  1374.  
  1375. A:      No.  main must be declared as returning an int, and as taking
  1376.         either zero or two arguments (of the appropriate type).  If
  1377.         you're calling exit() but still getting warnings, you'll have to
  1378.         insert a redundant return statement (or use some kind of
  1379.         "notreached" directive, if available).
  1380.  
  1381.         References: ANSI Sec. 2.1.2.2.1 pp. 7-8.
  1382.  
  1383. 5.11:   Is exit(status) truly equivalent to returning status from main?
  1384.  
  1385. A:      Yes, except under a few older, nonconforming systems.
  1386.  
  1387.         References: ANSI Sec. 2.1.2.2.3 p. 8.
  1388.  
  1389. 5.12:   Why does the ANSI Standard not guarantee more than six monocase
  1390.         characters of external identifier significance?
  1391.  
  1392. A:      The problem is older linkers which are neither under the control
  1393.         of the ANSI standard nor the C compiler developers on the
  1394.         systems which have them.  The limitation is only that
  1395.         identifiers be _significant_ in the first six characters, not
  1396.         that they be restricted to six characters in length.  This
  1397.         limitation is annoying, but certainly not unbearable, and is
  1398.         marked in the Standard as "obsolescent," i.e. a future revision
  1399.         will likely relax it.
  1400.  
  1401.         This concession to current, restrictive linkers really had to be
  1402.         made, no matter how vehemently some people oppose it.  (The
  1403.         Rationale notes that its retention was "most painful.")  If you
  1404.         disagree, or have thought of a trick by which a compiler
  1405.         burdened with a restrictive linker could present the C
  1406.         programmer with the appearance of more significance in external
  1407.         identifiers, read the excellently-worded section 3.1.2 in the
  1408.         X3.159 Rationale (see question 5.1), which discusses several
  1409.         such schemes and explains why they could not be mandated.
  1410.  
  1411.         References: ANSI Sec. 3.1.2 p. 21, Sec. 3.9.1 p. 96, Rationale
  1412.         Sec. 3.1.2 pp. 19-21.
  1413.  
  1414. 5.13:   What is the difference between memcpy and memmove?
  1415.  
  1416. A:      memmove offers guaranteed behavior if the source and destination
  1417.         arguments overlap.  memcpy makes no such guarantee, and may
  1418.         therefore be more efficiently implementable.  When in doubt,
  1419.         it's safer to use memmove.
  1420.  
  1421.         References: ANSI Secs. 4.11.2.1, 4.11.2.2, Rationale
  1422.         Sec. 4.11.2 .
  1423.  
  1424. 5.14:   My compiler is rejecting the simplest possible test programs,
  1425.         with all kinds of syntax errors.
  1426.  
  1427. A:      Perhaps it is a pre-ANSI compiler, unable to accept function
  1428.         prototypes and the like.
  1429.  
  1430. 5.15:   Why won't the Frobozz Magic C Compiler, which claims to be ANSI
  1431.         compliant, accept this code?  I know that the code is ANSI,
  1432.         because gcc accepts it.
  1433.  
  1434. A:      Most compilers support a few non-Standard extensions, gcc more
  1435.         so than most.  Are you sure that the code being rejected doesn't
  1436.         rely on such an extension?  It is usually a bad idea to perform
  1437.         experiments with a particular compiler to determine properties
  1438.         of a language; the applicable standard may permit variations, or
  1439.         the compiler may be wrong.
  1440.  
  1441. 5.16:   Is char a[3] = "abc"; legal?  What does it mean?
  1442.  
  1443. A:      Yes, it is legal; it declares an array of size three,
  1444.         initialized with the three characters 'a', 'b', and 'c', without
  1445.         the usual terminating '\0' character.
  1446.  
  1447.         References: ANSI Sec. 3.5.7 pp. 72-3.
  1448.  
  1449. 5.17:   What are #pragmas and what are they good for?
  1450.  
  1451. A:      The #pragma directive provides a single, well-defined "escape
  1452.         hatch" which can be used for all sorts of implementation-
  1453.         specific controls and extensions: source listing control,
  1454.         structure packing, warning suppression (like the old lint
  1455.         /* NOTREACHED */ comments), etc.
  1456.  
  1457.         References: ANSI Sec. 3.8.6 .
  1458.  
  1459.  
  1460. Section 6. C Preprocessor
  1461.  
  1462. 6.1:    How can I write a generic macro to swap two values?
  1463.  
  1464. A:      There is no good answer to this question.  If the values are
  1465.         integers, a well-known trick using exclusive-OR could perhaps be
  1466.         used, but it will not work for floating-point values or
  1467.         pointers, or if the two values are the same variable, (and the
  1468.         "obvious" supercompressed implementation for integral types
  1469.         a^=b^=a^=b is in fact illegal due to multiple side-effects,
  1470.         and...).  If the macro is intended to be used on values of
  1471.         arbitrary type (the usual goal), it cannot use a temporary,
  1472.         since it does not know what type of temporary it needs, and
  1473.         standard C does not provide a typeof operator.
  1474.  
  1475.         The best all-around solution is probably to forget about using a
  1476.         macro, unless you're willing to pass in the type as a third
  1477.         argument.
  1478.  
  1479. 6.2:    I have some old code that tries to construct identifiers with a
  1480.         macro like
  1481.  
  1482.                 #define Paste(a, b) a/**/b
  1483.  
  1484.         but it doesn't work any more.
  1485.  
  1486. A:      That comments disappeared entirely and could therefore be used
  1487.         for token pasting was an undocumented feature of some early
  1488.         preprocessor implementations, notably Reiser's.  ANSI affirms
  1489.         (as did K&R) that comments are replaced with white space.
  1490.         However, since the need for pasting tokens was demonstrated and
  1491.         real, ANSI introduced a well-defined token-pasting operator, ##,
  1492.         which can be used like this:
  1493.  
  1494.                 #define Paste(a, b) a##b
  1495.  
  1496.         (See also question 5.4.)
  1497.  
  1498.         References: ANSI Sec. 3.8.3.3 p. 91, Rationale pp. 66-7.
  1499.  
  1500. 6.3:    What's the best way to write a multi-statement cpp macro?
  1501.  
  1502. A:      The usual goal is to write a macro that can be invoked as if it
  1503.         were a single function-call statement.  This means that the
  1504.         "caller" will be supplying the final semicolon, so the macro
  1505.         body should not.  The macro body cannot be a simple brace-
  1506.         delineated compound statement, because syntax errors would
  1507.         result if it were invoked (apparently as a single statement, but
  1508.         with a resultant extra semicolon) as the if branch of an if/else
  1509.         statement with an explicit else clause.
  1510.  
  1511.         The traditional solution is to use
  1512.  
  1513.                 #define Func() do { \
  1514.                         /* declarations */ \
  1515.                         stmt1; \
  1516.                         stmt2; \
  1517.                         /* ... */ \
  1518.                         } while(0)      /* (no trailing ; ) */
  1519.  
  1520.         When the "caller" appends a semicolon, this expansion becomes a
  1521.         single statement regardless of context.  (An optimizing compiler
  1522.         will remove any "dead" tests or branches on the constant
  1523.         condition 0, although lint may complain.)
  1524.  
  1525.         If all of the statements in the intended macro are simple
  1526.         expressions, with no declarations or loops, another technique is
  1527.         to write a single, parenthesized expression using one or more
  1528.         comma operators.  (See the example under question 6.10 below.
  1529.         This technique also allows a value to be "returned.")
  1530.  
  1531.         References: CT&P Sec. 6.3 pp. 82-3.
  1532.  
  1533. 6.4:    Is it acceptable for one header file to #include another?
  1534.  
  1535. A:      There has been considerable debate surrounding this question.
  1536.         Many people believe that "nested #include files" are to be
  1537.         avoided: the prestigious Indian Hill Style Guide (see question
  1538.         14.3) disparages them; they can make it harder to find relevant
  1539.         definitions; they can lead to multiple-declaration errors if a
  1540.         file is #included twice; and they make manual Makefile
  1541.         maintenance very difficult.  On the other hand, they make it
  1542.         possible to use header files in a modular way (a header file
  1543.         #includes what it needs itself, rather than requiring each
  1544.         #includer to do so, a requirement that can lead to intractable
  1545.         headaches); a tool like grep (or a tags file) makes it easy to
  1546.         find definitions no matter where they are; a popular trick:
  1547.  
  1548.                 #ifndef HEADER_FILE_NAME
  1549.                 #define HEADER_FILE_NAME
  1550.                 ...header file contents...
  1551.                 #endif
  1552.  
  1553.         makes a header file "idempotent" so that it can safely be
  1554.         #included multiple times; and automated Makefile maintenance
  1555.         tools (which are a virtual necessity in large projects anyway)
  1556.         handle dependency generation in the face of nested #include
  1557.         files easily.  See also section 14.
  1558.  
  1559. 6.5:    Does the sizeof operator work in preprocessor #if directives?
  1560.  
  1561. A:      No.  Preprocessing happens during an earlier pass of
  1562.         compilation, before type names have been parsed.  Consider using
  1563.         the predefined constants in ANSI's <limits.h>, if applicable, or
  1564.         a "configure" script, instead.  (Better yet, try to write code
  1565.         which is inherently insensitive to type sizes.)
  1566.  
  1567.         References: ANSI Sec. 2.1.1.2 pp. 6-7, Sec. 3.8.1 p. 87
  1568.         footnote 83.
  1569.  
  1570. 6.6:    How can I use a preprocessor #if expression to tell if a machine
  1571.         is big-endian or little-endian?
  1572.  
  1573. A:      You probably can't.  (Preprocessor arithmetic uses only long
  1574.         ints, and there is no concept of addressing.)  Are you sure you
  1575.         need to know the machine's endianness explicitly?  Usually it's
  1576.         better to write code which doesn't care.
  1577.  
  1578. 6.7:    I've got this tricky processing I want to do at compile time and
  1579.         I can't figure out a way to get cpp to do it.
  1580.  
  1581. A:      cpp is not intended as a general-purpose preprocessor.  Rather
  1582.         than forcing it to do something inappropriate, consider writing
  1583.         your own little special-purpose preprocessing tool, instead.
  1584.         You can easily get a utility like make(1) to run it for you
  1585.         automatically.
  1586.  
  1587.         If you are trying to preprocess something other than C, consider
  1588.         using a general-purpose preprocessor (such as m4).
  1589.  
  1590. 6.8:    I have some code which contains far too many #ifdef's for my
  1591.         taste.  How can I preprocess the code to leave only one
  1592.         conditional compilation set, without running it through cpp and
  1593.         expanding all of the #include's and #define's as well?
  1594.  
  1595. A:      There is a program floating around called unifdef which does
  1596.         exactly this.  (See question 17.8.)
  1597.  
  1598. 6.9:    How can I list all of the pre#defined identifiers?
  1599.  
  1600. A:      There's no standard way, although it is a frequent need.  The
  1601.         most expedient way is probably to extract printable strings from
  1602.         the compiler or preprocessor executable with something like the
  1603.         Unix strings(1) utility.
  1604.  
  1605. 6.10:   How can I write a cpp macro which takes a variable number of
  1606.         arguments?
  1607.  
  1608. A:      One popular trick is to define the macro with a single argument,
  1609.         and call it with a double set of parentheses, which appear to
  1610.         the preprocessor to indicate a single argument:
  1611.  
  1612.                 #define DEBUG(args) (printf("DEBUG: "), printf args)
  1613.  
  1614.                 if(n != 0) DEBUG(("n is %d\n", n));
  1615.  
  1616.         The obvious disadvantage is that the caller must always remember
  1617.         to use the extra parentheses.  Another solution is to use
  1618.         different macros (DEBUG1, DEBUG2, etc.) depending on the number
  1619.         of arguments.  (It is often better to use a bona-fide function,
  1620.         which can take a variable number of arguments in a well-defined
  1621.         way.  See questions 7.1 and 7.2 below.)
  1622.  
  1623.  
  1624. Section 7. Variable-Length Argument Lists
  1625.  
  1626. 7.1:    How can I write a function that takes a variable number of
  1627.         arguments?
  1628.  
  1629. A:      Use the <stdarg.h> header (or, if you must, the older
  1630.         <varargs.h>).
  1631.  
  1632.         Here is a function which concatenates an arbitrary number of
  1633.         strings into malloc'ed memory:
  1634.  
  1635.                 #include <stdlib.h>             /* for malloc, NULL, size_t */
  1636.                 #include <stdarg.h>             /* for va_ stuff */
  1637.                 #include <string.h>             /* for strcat et al */
  1638.  
  1639.                 char *vstrcat(char *first, ...)
  1640.                 {
  1641.                         size_t len = 0;
  1642.                         char *retbuf;
  1643.                         va_list argp;
  1644.                         char *p;
  1645.  
  1646.                         if(first == NULL)
  1647.                                 return NULL;
  1648.  
  1649.                         len = strlen(first);
  1650.  
  1651.                         va_start(argp, first);
  1652.  
  1653.                         while((p = va_arg(argp, char *)) != NULL)
  1654.                                 len += strlen(p);
  1655.  
  1656.                         va_end(argp);
  1657.  
  1658.                         retbuf = malloc(len + 1);       /* +1 for trailing \0 */
  1659.  
  1660.                         if(retbuf == NULL)
  1661.                                 return NULL;            /* error */
  1662.  
  1663.                         (void)strcpy(retbuf, first);
  1664.  
  1665.                         va_start(argp, first);
  1666.  
  1667.                         while((p = va_arg(argp, char *)) != NULL)
  1668.                                 (void)strcat(retbuf, p);
  1669.  
  1670.                         va_end(argp);
  1671.  
  1672.                         return retbuf;
  1673.                 }
  1674.  
  1675.         Usage is something like
  1676.  
  1677.                 char *str = vstrcat("Hello, ", "world!", (char *)NULL);
  1678.  
  1679.         Note the cast on the last argument.  (Also note that the caller
  1680.         must free the returned, malloc'ed storage.)
  1681.  
  1682.         Under a pre-ANSI compiler, rewrite the function definition
  1683.         without a prototype ("char *vstrcat(first) char *first; {"),
  1684.         include <stdio.h> rather than <stdlib.h>, add "extern
  1685.         char *malloc();", and use int instead of size_t.  You may also
  1686.         have to delete the (void) casts, and use the older varargs
  1687.         package instead of stdarg.  See the next question for hints.
  1688.  
  1689.         Remember that in variable-length argument lists, function
  1690.         prototypes do not supply parameter type information; therefore,
  1691.         default argument promotions apply (see question 5.7), and null
  1692.         pointer arguments must be typed explicitly (see question 1.2).
  1693.  
  1694.         References: K&R II Sec. 7.3 p. 155, Sec. B7 p. 254; H&S
  1695.         Sec. 13.4 pp. 286-9; ANSI Secs. 4.8 through 4.8.1.3 .
  1696.  
  1697. 7.2:    How can I write a function that takes a format string and a
  1698.         variable number of arguments, like printf, and passes them to
  1699.         printf to do most of the work?
  1700.  
  1701. A:      Use vprintf, vfprintf, or vsprintf.
  1702.  
  1703.         Here is an "error" routine which prints an error message,
  1704.         preceded by the string "error: " and terminated with a newline:
  1705.  
  1706.                 #include <stdio.h>
  1707.                 #include <stdarg.h>
  1708.  
  1709.                 void
  1710.                 error(char *fmt, ...)
  1711.                 {
  1712.                         va_list argp;
  1713.                         fprintf(stderr, "error: ");
  1714.                         va_start(argp, fmt);
  1715.                         vfprintf(stderr, fmt, argp);
  1716.                         va_end(argp);
  1717.                         fprintf(stderr, "\n");
  1718.                 }
  1719.  
  1720.         To use the older <varargs.h> package, instead of <stdarg.h>,
  1721.         change the function header to:
  1722.  
  1723.                 void error(va_alist)
  1724.                 va_dcl
  1725.                 {
  1726.                         char *fmt;
  1727.  
  1728.         change the va_start line to
  1729.  
  1730.                 va_start(argp);
  1731.  
  1732.         and add the line
  1733.  
  1734.                 fmt = va_arg(argp, char *);
  1735.  
  1736.         between the calls to va_start and vfprintf.  (Note that there is
  1737.         no semicolon after va_dcl.)
  1738.  
  1739.         References: K&R II Sec. 8.3 p. 174, Sec. B1.2 p. 245; H&S
  1740.         Sec. 17.12 p. 337; ANSI Secs. 4.9.6.7, 4.9.6.8, 4.9.6.9 .
  1741.  
  1742. 7.3:    How can I discover how many arguments a function was actually
  1743.         called with?
  1744.  
  1745. A:      This information is not available to a portable program.  Some
  1746.         systems provide a nonstandard nargs() function, but its use is
  1747.         questionable, since it typically returns the number of words
  1748.         passed, not the number of arguments.  (Floating point values and
  1749.         structures are usually passed as several words.)
  1750.  
  1751.         Any function which takes a variable number of arguments must be
  1752.         able to determine from the arguments themselves how many of them
  1753.         there are.  printf-like functions do this by looking for
  1754.         formatting specifiers (%d and the like) in the format string
  1755.         (which is why these functions fail badly if the format string
  1756.         does not match the argument list).  Another common technique
  1757.         (useful when the arguments are all of the same type) is to use a
  1758.         sentinel value (often 0, -1, or an appropriately-cast null
  1759.         pointer) at the end of the list (see the execl and vstrcat
  1760.         examples under questions 1.2 and 7.1 above).
  1761.  
  1762. 7.4:    I can't get the va_arg macro to pull in an argument of type
  1763.         pointer-to-function.
  1764.  
  1765. A:      The type-rewriting games which the va_arg macro typically plays
  1766.         are stymied by overly-complicated types such as pointer-to-
  1767.         function.  If you use a typedef for the function pointer type,
  1768.         however, all will be well.
  1769.  
  1770.         References: ANSI Sec. 4.8.1.2 p. 124.
  1771.  
  1772. 7.5:    How can I write a function which takes a variable number of
  1773.         arguments and passes them to some other function (which takes a
  1774.         variable number of arguments)?
  1775.  
  1776. A:      In general, you cannot.  You must provide a version of that
  1777.         other function which accepts a va_list pointer, as does vfprintf
  1778.         in the example above.  If the arguments must be passed directly
  1779.         as actual arguments (not indirectly through a va_list pointer)
  1780.         to another function which is itself variadic (for which you do
  1781.         not have the option of creating an alternate, va_list-accepting
  1782.         version) no portable solution is possible.  (The problem can be
  1783.         solved by resorting to machine-specific assembly language.)
  1784.  
  1785. 7.6:    How can I call a function with an argument list built up at run
  1786.         time?
  1787.  
  1788. A:      There is no guaranteed or portable way to do this.  If you're
  1789.         curious, ask this list's editor, who has a few wacky ideas you
  1790.         could try...  (See also question 16.10.)
  1791.  
  1792.  
  1793. Section 8. Boolean Expressions and Variables
  1794.  
  1795. 8.1:    What is the right type to use for boolean values in C?  Why
  1796.         isn't it a standard type?  Should #defines or enums be used for
  1797.         the true and false values?
  1798.  
  1799. A:      C does not provide a standard boolean type, because picking one
  1800.         involves a space/time tradeoff which is best decided by the
  1801.         programmer.  (Using an int for a boolean may be faster, while
  1802.         using char may save data space.)
  1803.  
  1804.         The choice between #defines and enums is arbitrary and not
  1805.         terribly interesting (see also question 9.1).  Use any of
  1806.  
  1807.                 #define TRUE  1                 #define YES 1
  1808.                 #define FALSE 0                 #define NO  0
  1809.  
  1810.                 enum bool {false, true};        enum bool {no, yes};
  1811.  
  1812.         or use raw 1 and 0, as long as you are consistent within one
  1813.         program or project.  (An enum may be preferable if your debugger
  1814.         expands enum values when examining variables.)
  1815.  
  1816.         Some people prefer variants like
  1817.  
  1818.                 #define TRUE (1==1)
  1819.                 #define FALSE (!TRUE)
  1820.  
  1821.         or define "helper" macros such as
  1822.  
  1823.                 #define Istrue(e) ((e) != 0)
  1824.  
  1825.         These don't buy anything (see question 8.2 below; see also
  1826.         question 1.6).
  1827.  
  1828. 8.2:    Isn't #defining TRUE to be 1 dangerous, since any nonzero value
  1829.         is considered "true" in C?  What if a built-in boolean or
  1830.         relational operator "returns" something other than 1?
  1831.  
  1832. A:      It is true (sic) that any nonzero value is considered true in C,
  1833.         but this applies only "on input", i.e. where a boolean value is
  1834.         expected.  When a boolean value is generated by a built-in
  1835.         operator, it is guaranteed to be 1 or 0.  Therefore, the test
  1836.  
  1837.                 if((a == b) == TRUE)
  1838.  
  1839.         will work as expected (as long as TRUE is 1), but it is
  1840.         obviously silly.  In general, explicit tests against TRUE and
  1841.         FALSE are undesirable, because some library functions (notably
  1842.         isupper, isalpha, etc.) return, on success, a nonzero value
  1843.         which is _not_ necessarily 1.  (Besides, if you believe that
  1844.         "if((a == b) == TRUE)" is an improvement over "if(a == b)", why
  1845.         stop there?  Why not use "if(((a == b) == TRUE) == TRUE)"?)  A
  1846.         good rule of thumb is to use TRUE and FALSE (or the like) only
  1847.         for assignment to a Boolean variable, or as the return value
  1848.         from a Boolean function, never in a comparison.
  1849.  
  1850.         The preprocessor macros TRUE and FALSE (and, of course, NULL)
  1851.         are used for code readability, not because the underlying values
  1852.         might ever change.  (See also question 1.7.)
  1853.  
  1854.         References: K&R I Sec. 2.7 p. 41; K&R II Sec. 2.6 p. 42,
  1855.         Sec. A7.4.7 p. 204, Sec. A7.9 p. 206; ANSI Secs. 3.3.3.3, 3.3.8,
  1856.         3.3.9, 3.3.13, 3.3.14, 3.3.15, 3.6.4.1, 3.6.5; Achilles and the
  1857.         Tortoise.
  1858.  
  1859.  
  1860. Section 9. Structs, Enums, and Unions
  1861.  
  1862. 9.1:    What is the difference between an enum and a series of
  1863.         preprocessor #defines?
  1864.  
  1865. A:      At the present time, there is little difference.  Although many
  1866.         people might have wished otherwise, the ANSI standard says that
  1867.         enumerations may be freely intermixed with integral types,
  1868.         without errors.  (If such intermixing were disallowed without
  1869.         explicit casts, judicious use of enums could catch certain
  1870.         programming errors.)
  1871.  
  1872.         Some advantages of enums are that the numeric values are
  1873.         automatically assigned, that a debugger may be able to display
  1874.         the symbolic values when enum variables are examined, and that
  1875.         they obey block scope.  (A compiler may also generate nonfatal
  1876.         warnings when enums and ints are indiscriminately mixed, since
  1877.         doing so can still be considered bad style even though it is not
  1878.         strictly illegal).  A disadvantage is that the programmer has
  1879.         little control over the size (or over those nonfatal warnings).
  1880.  
  1881.         References: K&R II Sec. 2.3 p. 39, Sec. A4.2 p. 196; H&S
  1882.         Sec. 5.5 p. 100; ANSI Secs. 3.1.2.5, 3.5.2, 3.5.2.2 .
  1883.  
  1884. 9.2:    I heard that structures could be assigned to variables and
  1885.         passed to and from functions, but K&R I says not.
  1886.  
  1887. A:      What K&R I said was that the restrictions on struct operations
  1888.         would be lifted in a forthcoming version of the compiler, and in
  1889.         fact struct assignment and passing were fully functional in
  1890.         Ritchie's compiler even as K&R I was being published.  Although
  1891.         a few early C compilers lacked struct assignment, all modern
  1892.         compilers support it, and it is part of the ANSI C standard, so
  1893.         there should be no reluctance to use it.
  1894.  
  1895.         References: K&R I Sec. 6.2 p. 121; K&R II Sec. 6.2 p. 129; H&S
  1896.         Sec. 5.6.2 p. 103; ANSI Secs. 3.1.2.5, 3.2.2.1, 3.3.16 .
  1897.  
  1898. 9.3:    How does struct passing and returning work?
  1899.  
  1900. A:      When structures are passed as arguments to functions, the entire
  1901.         struct is typically pushed on the stack, using as many words as
  1902.         are required.  (Programmers often choose to use pointers to
  1903.         structures instead, precisely to avoid this overhead.)
  1904.  
  1905.         Structures are often returned from functions in a location
  1906.         pointed to by an extra, compiler-supplied "hidden" argument to
  1907.         the function.  Some older compilers used a special, static
  1908.         location for structure returns, although this made struct-valued
  1909.         functions nonreentrant, which ANSI C disallows.
  1910.  
  1911.         References: ANSI Sec. 2.2.3 p. 13.
  1912.  
  1913. 9.4:    The following program works correctly, but it dumps core after
  1914.         it finishes.  Why?
  1915.  
  1916.                 struct list
  1917.                         {
  1918.                         char *item;
  1919.                         struct list *next;
  1920.                         }
  1921.  
  1922.                 /* Here is the main program. */
  1923.  
  1924.                 main(argc, argv)
  1925.                 ...
  1926.  
  1927. A:      A missing semicolon causes the compiler to believe that main
  1928.         returns a structure.  (The connection is hard to see because of
  1929.         the intervening comment.)  Since struct-valued functions are
  1930.         usually implemented by adding a hidden return pointer, the
  1931.         generated code for main() tries to accept three arguments,
  1932.         although only two are passed (in this case, by the C start-up
  1933.         code).  See also question 17.15.
  1934.  
  1935.         References: CT&P Sec. 2.3 pp. 21-2.
  1936.  
  1937. 9.5:    Why can't you compare structs?
  1938.  
  1939. A:      There is no reasonable way for a compiler to implement struct
  1940.         comparison which is consistent with C's low-level flavor.  A
  1941.         byte-by-byte comparison could be invalidated by random bits
  1942.         present in unused "holes" in the structure (such padding is used
  1943.         to keep the alignment of later fields correct).  A field-by-
  1944.         field comparison would require unacceptable amounts of
  1945.         repetitive, in-line code for large structures.
  1946.  
  1947.         If you want to compare two structures, you must write your own
  1948.         function to do so.  C++ would let you arrange for the ==
  1949.         operator to map to your function.
  1950.  
  1951.         References: K&R II Sec. 6.2 p. 129; H&S Sec. 5.6.2 p. 103; ANSI
  1952.         Rationale Sec. 3.3.9 p. 47.
  1953.  
  1954. 9.6:    I came across some code that declared a structure like this:
  1955.  
  1956.                 struct name
  1957.                         {
  1958.                         int namelen;
  1959.                         char name[1];
  1960.                         };
  1961.  
  1962.         and then did some tricky allocation to make the name array act
  1963.         like it had several elements.  Is this legal and/or portable?
  1964.  
  1965. A:      This technique is popular, although Dennis Ritchie has called it
  1966.         "unwarranted chumminess with the compiler."  The ANSI C standard
  1967.         allows it only implicitly.  It seems to be portable to all known
  1968.         implementations.  (Compilers which check array bounds carefully
  1969.         might issue warnings.)
  1970.  
  1971.         References: ANSI Rationale Sec. 3.5.4.2 pp. 54-5.
  1972.  
  1973. 9.7:    How can I determine the byte offset of a field within a
  1974.         structure?
  1975.  
  1976. A:      ANSI C defines the offsetof macro, which should be used if
  1977.         available; see <stddef.h>.  If you don't have it, a suggested
  1978.         implementation is
  1979.  
  1980.                 #define offsetof(type, mem) ((size_t) \
  1981.                         ((char *)&((type *) 0)->mem - (char *)((type *) 0)))
  1982.  
  1983.         This implementation is not 100% portable; some compilers may
  1984.         legitimately refuse to accept it.
  1985.  
  1986.         See the next question for a usage hint.
  1987.  
  1988.         References: ANSI Sec. 4.1.5, Rationale Sec. 3.5.4.2 p. 55.
  1989.  
  1990. 9.8:    How can I access structure fields by name at run time?
  1991.  
  1992. A:      Build a table of names and offsets, using the offsetof() macro.
  1993.         The offset of field b in struct a is
  1994.  
  1995.                 offsetb = offsetof(struct a, b)
  1996.  
  1997.         If structp is a pointer to an instance of this structure, and b
  1998.         is an int field with offset as computed above, b's value can be
  1999.         set indirectly with
  2000.  
  2001.                 *(int *)((char *)structp + offsetb) = value;
  2002.  
  2003. 9.9:    Why does sizeof report a larger size than I expect for a
  2004.         structure type, as if there was padding at the end?
  2005.  
  2006. A:      Structures may have this padding (as well as internal padding;
  2007.         see also question 9.5), so that alignment properties will be
  2008.         preserved when an array of contiguous structures is allocated.
  2009.  
  2010. 9.10:   My compiler is leaving holes in structures, which is wasting
  2011.         space and preventing "binary" I/O to external data files.  Can I
  2012.         turn off the padding, or otherwise control the alignment of
  2013.         structs?
  2014.  
  2015. A:      Your compiler may provide an extension to give you this control
  2016.         (perhaps a #pragma), but there is no standard method.  See also
  2017.         question 17.2.
  2018.  
  2019. 9.11:   Can I initialize unions?
  2020.  
  2021. A:      ANSI Standard C allows an initializer for the first member of a
  2022.         union.  There is no standard way of initializing the other
  2023.         members (nor, under a pre-ANSI compiler, is there generally any
  2024.         way of initializing any of them).
  2025.  
  2026.  
  2027. Section 10. Declarations
  2028.  
  2029. 10.1:   How do you decide which integer type to use?
  2030.  
  2031. A:      If you might need large values (above 32767 or below -32767),
  2032.         use long.  Otherwise, if space is very important (there are
  2033.         large arrays or many structures), use short.  Otherwise, use
  2034.         int.  If well-defined overflow characteristics are important
  2035.         and/or negative values are not, use the corresponding unsigned
  2036.         types.  (But beware of mixing signed and unsigned in
  2037.         expressions.)  Similar arguments apply when deciding between
  2038.         float and double.
  2039.  
  2040.         Although char or unsigned char can be used as a "tiny" int type,
  2041.         doing so is often more trouble than it's worth, due to
  2042.         unpredictable sign extension and increased code size.
  2043.  
  2044.         These rules obviously don't apply if the address of a variable
  2045.         is taken and must have a particular type.
  2046.  
  2047.         If for some reason you need to declare something with an _exact_
  2048.         size (usually the only good reason for doing so is when
  2049.         attempting to conform to some externally-imposed storage layout,
  2050.         but see question 17.2), be sure to encapsulate the choice behind
  2051.         an appropriate typedef.
  2052.  
  2053. 10.2:   What should the 64-bit type on new, 64-bit machines be?
  2054.  
  2055. A:      Some vendors of C products for 64-bit machines support 64-bit
  2056.         long ints.  Others fear that too much existing code depends on
  2057.         sizeof(int) == sizeof(long) == 32 bits, and introduce a new 64-
  2058.         bit long long int type instead.
  2059.  
  2060.         Programmers interested in writing portable code should therefore
  2061.         insulate their 64-bit type needs behind appropriate typedefs.
  2062.         Vendors who feel compelled to introduce a new long long int type
  2063.         should advertise it as being "at least 64 bits" (which is truly
  2064.         new; a type traditional C doesn't have), and not "exactly 64
  2065.         bits."
  2066.  
  2067. 10.3:   I can't seem to define a linked list successfully.  I tried
  2068.  
  2069.                 typedef struct
  2070.                         {
  2071.                         char *item;
  2072.                         NODEPTR next;
  2073.                         } *NODEPTR;
  2074.  
  2075.         but the compiler gave me error messages.  Can't a struct in C
  2076.         contain a pointer to itself?
  2077.  
  2078. A:      Structs in C can certainly contain pointers to themselves; the
  2079.         discussion and example in section 6.5 of K&R make this clear.
  2080.         The problem with this example is that the NODEPTR typedef is not
  2081.         complete at the point where the "next" field is declared.  To
  2082.         fix it, first give the structure a tag ("struct node").  Then,
  2083.         declare the "next" field as "struct node *next;", and/or move
  2084.         the typedef declaration wholly before or wholly after the struct
  2085.         declaration.  One corrected version would be
  2086.  
  2087.                 struct node
  2088.                         {
  2089.                         char *item;
  2090.                         struct node *next;
  2091.                         };
  2092.  
  2093.                 typedef struct node *NODEPTR;
  2094.  
  2095.         , and there are at least three other equivalently correct ways
  2096.         of arranging it.
  2097.  
  2098.         A similar problem, with a similar solution, can arise when
  2099.         attempting to declare a pair of typedef'ed mutually recursive
  2100.         structures.
  2101.  
  2102.         References: K&R I Sec. 6.5 p. 101; K&R II Sec. 6.5 p. 139; H&S
  2103.         Sec. 5.6.1 p. 102; ANSI Sec. 3.5.2.3 .
  2104.  
  2105. 10.4:   How do I declare an array of pointers to functions returning
  2106.         pointers to functions returning pointers to characters?
  2107.  
  2108. A:      This question can be answered in at least three ways (all
  2109.         declare the hypothetical array with 5 elements):
  2110.  
  2111.         1.  char *(*(*a[5])())();
  2112.  
  2113.         2.  Build the declaration up in stages, using typedefs:
  2114.  
  2115.                 typedef char *pc;       /* pointer to char */
  2116.                 typedef pc fpc();       /* function returning pointer to char */
  2117.                 typedef fpc *pfpc;      /* pointer to above */
  2118.                 typedef pfpc fpfpc();   /* function returning... */
  2119.                 typedef fpfpc *pfpfpc;  /* pointer to... */
  2120.                 pfpfpc a[5];            /* array of... */
  2121.  
  2122.         3.  Use the cdecl program, which turns English into C and vice
  2123.             versa:
  2124.  
  2125.                 cdecl> declare a as array 5 of pointer to function returning
  2126.                          pointer to function returning pointer to char
  2127.                 char *(*(*a[5])())()
  2128.  
  2129.             cdecl can also explain complicated declarations, help with
  2130.             casts, and indicate which set of parentheses the arguments
  2131.             go in (for complicated function definitions, like the
  2132.             above).  Versions of cdecl are in volume 14 of
  2133.             comp.sources.unix (see question 17.8) and K&R II.
  2134.  
  2135.         Any good book on C should explain how to read these complicated
  2136.         C declarations "inside out" to understand them ("declaration
  2137.         mimics use").
  2138.  
  2139.         References: K&R II Sec. 5.12 p. 122; H&S Sec. 5.10.1 p. 116.
  2140.  
  2141. 10.5:   I'm building a state machine with a bunch of functions, one for
  2142.         each state.  I want to implement state transitions by having
  2143.         each function return a pointer to the next state function.  I
  2144.         find a limitation in C's declaration mechanism: there's no way
  2145.         to declare these functions as returning a pointer to a function
  2146.         returning a pointer to a function returning a pointer to a
  2147.         function...
  2148.  
  2149. A:      You can't do it directly.  Either have the function return a
  2150.         generic function pointer type, and apply a cast before calling
  2151.         through it; or have it return a structure containing only a
  2152.         pointer to a function returning that structure.
  2153.  
  2154. 10.6:   What's the best way to declare and define global variables?
  2155.  
  2156. A:      First, though there can be many _declarations_ (and in many
  2157.         translation units) of a single "global" (strictly speaking,
  2158.         "external") variable (or function), there must be exactly one
  2159.         _definition_.  (The definition is the declaration that actually
  2160.         allocates space, and provides an initialization value, if any.)
  2161.         It is best to place the definition in some central (to the
  2162.         program, or to the module) .c file, with an external declaration
  2163.         in a header (".h") file, which is #included wherever the
  2164.         declaration is needed.  The .c file containing the definition
  2165.         should also #include the header file containing the external
  2166.         declaration, so that the compiler can check that the
  2167.         declarations match.
  2168.  
  2169.         This rule promotes a high degree of portability, and is
  2170.         consistent with the requirements of the ANSI C Standard.  Note
  2171.         that Unix compilers and linkers typically use a "common model"
  2172.         which allows multiple (uninitialized) definitions.  A few very
  2173.         odd systems may require an explicit initializer to distinguish a
  2174.         definition from an external declaration.
  2175.  
  2176.         It is possible to use preprocessor tricks to arrange that the
  2177.         declaration need only be typed once, in the header file, and
  2178.         "turned into" a definition, during exactly one #inclusion, via a
  2179.         special #define.
  2180.  
  2181.         References: K&R I Sec. 4.5 pp. 76-7; K&R II Sec. 4.4 pp. 80-1;
  2182.         ANSI Sec. 3.1.2.2 (esp. Rationale), Secs. 3.7, 3.7.2,
  2183.         Sec. F.5.11 .
  2184.  
  2185. 10.7:   I finally figured out the syntax for declaring pointers to
  2186.         functions, but now how do I initialize one?
  2187.  
  2188. A:      Use something like
  2189.  
  2190.                 extern int func();
  2191.                 int (*fp)() = func;
  2192.  
  2193.         When the name of a function appears in an expression but is not
  2194.         being called (i.e. is not followed by a "("), it "decays" into a
  2195.         pointer (i.e. it has its address implicitly taken), much as an
  2196.         array name does.
  2197.  
  2198.         An explicit extern declaration for the function is normally
  2199.         needed, since implicit external function declaration does not
  2200.         happen in this case (again, because the function name is not
  2201.         followed by a "(").
  2202.  
  2203. 10.8:   I've seen different methods used for calling through pointers to
  2204.         functions.  What's the story?
  2205.  
  2206. A:      Originally, a pointer to a function had to be "turned into" a
  2207.         "real" function, with the * operator (and an extra pair of
  2208.         parentheses, to keep the precedence straight), before calling:
  2209.  
  2210.                 int r, func(), (*fp)() = func;
  2211.                 r = (*fp)();
  2212.  
  2213.         It can also be argued that functions are always called through
  2214.         pointers, but that "real" functions decay implicitly into
  2215.         pointers (in expressions, as they do in initializations) and so
  2216.         cause no trouble.  This reasoning, made widespread through pcc
  2217.         and adopted in the ANSI standard, means that
  2218.  
  2219.                 r = fp();
  2220.  
  2221.         is legal and works correctly, whether fp is a function or a
  2222.         pointer to one.  (The usage has always been unambiguous; there
  2223.         is nothing you ever could have done with a function pointer
  2224.         followed by an argument list except call through it.)  An
  2225.         explicit * is harmless, and still allowed (and recommended, if
  2226.         portability to older compilers is important).
  2227.  
  2228.         References: ANSI Sec. 3.3.2.2 p. 41, Rationale p. 41.
  2229.  
  2230.  
  2231. Section 11. Stdio
  2232.  
  2233. 11.1:   Why doesn't this code:
  2234.  
  2235.                 char c;
  2236.                 while((c = getchar()) != EOF)...
  2237.  
  2238.         work?
  2239.  
  2240. A:      For one thing, the variable to hold getchar's return value must
  2241.         be an int.  getchar can return all possible character values, as
  2242.         well as EOF.  By passing getchar's return value through a char,
  2243.         either a normal character might be misinterpreted as EOF, or the
  2244.         EOF might be altered and so never seen.
  2245.  
  2246.         References: CT&P Sec. 5.1 p. 70.
  2247.  
  2248. 11.2:   Why doesn't the code scanf("%d", i); work?
  2249.  
  2250. A:      You must always pass addresses (in this case, &i) to scanf.
  2251.  
  2252. 11.3:   Why doesn't this code:
  2253.  
  2254.                 double d;
  2255.                 scanf("%f", &d);
  2256.  
  2257.         work?
  2258.  
  2259. A:      With scanf, use %lf for values of type double, and %f for float.
  2260.         (Note the discrepancy with printf, which uses %f for both double
  2261.         and float, due to C's default argument promotion rules.)
  2262.  
  2263. 11.4:   Why won't the code
  2264.  
  2265.                 while(!feof(fp))
  2266.                         fgets(buf, MAXLINE, fp);
  2267.  
  2268.         work?
  2269.  
  2270. A:      C's I/O is not like Pascal's.  EOF is only indicated _after_ an
  2271.         input routine has tried to read, and has reached end-of-file.
  2272.         Usually, you should just check the return value of the input
  2273.         routine (fgets in this case); feof() is rarely needed.
  2274.  
  2275. 11.5:   Why does everyone say not to use gets()?
  2276.  
  2277. A:      It cannot be told the size of the buffer it's to read into, so
  2278.         it cannot be prevented from overflowing that buffer.
  2279.  
  2280. 11.6:   Why does errno contain ENOTTY after a call to printf?
  2281.  
  2282. A:      Many implementations of the stdio package adjust their behavior
  2283.         slightly if stdout is a terminal.  To make the determination,
  2284.         these implementations perform an operation which fails (with
  2285.         ENOTTY) if stdout is not a terminal.  Although the output
  2286.         operation goes on to complete successfully, errno still contains
  2287.         ENOTTY.
  2288.  
  2289.         References: CT&P Sec. 5.4 p. 73.
  2290.  
  2291. 11.7:   My program's prompts and intermediate output don't always show
  2292.         up on the screen, especially when I pipe the output through
  2293.         another program.
  2294.  
  2295. A:      It is best to use an explicit fflush(stdout) whenever output
  2296.         should definitely be visible.  Several mechanisms attempt to
  2297.         perform the fflush for you, at the "right time," but they tend
  2298.         to apply only when stdout is a terminal.  (See question 11.6.)
  2299.  
  2300. 11.8:   When I read from the keyboard with scanf, it seems to hang until
  2301.         I type one extra line of input.
  2302.  
  2303. A:      scanf was designed for free-format input, which is seldom what
  2304.         you want when reading from the keyboard.  In particular, "\n" in
  2305.         a format string does _not_ mean to expect a newline, but rather
  2306.         to read and discard characters as long as each is a whitespace
  2307.         character.
  2308.  
  2309.         A related problem is that unexpected non-numeric input can cause
  2310.         scanf to "jam."  Because of these problems, it is usually better
  2311.         to use fgets() to read a whole line, and then use sscanf or
  2312.         other string functions to pick apart the line buffer.  If you do
  2313.         use sscanf, don't forget to check the return value to make sure
  2314.         that the expected number of items were found.
  2315.  
  2316. 11.9:   I'm trying to update a file in place, by using fopen mode "r+",
  2317.         then reading a certain string, and finally writing back a
  2318.         modified string, but it's not working.
  2319.  
  2320. A:      Be sure to call fseek before you write, both to seek back to the
  2321.         beginning of the string you're trying to overwrite, and because
  2322.         an fseek or fflush is always required between reading and
  2323.         writing in the read/write "+" modes.
  2324.  
  2325.         References: ANSI Sec. 4.9.5.3 p. 131.
  2326.  
  2327. 11.10:  How can I read one character at a time, without waiting for the
  2328.         RETURN key?
  2329.  
  2330. A:      See question 16.1.
  2331.  
  2332. 11.11:  How can I flush pending input so that a user's typeahead isn't
  2333.         read at the next prompt?  Will fflush(stdin) work?
  2334.  
  2335. A:      fflush is defined only for output streams.  Since its definition
  2336.         of "flush" is to complete the writing of buffered characters
  2337.         (not to discard them), discarding unread input would not be an
  2338.         analogous meaning for fflush on input streams.  There is no
  2339.         standard way to discard unread characters from a stdio input
  2340.         buffer, nor would such a way be sufficient; unread characters
  2341.         can also accumulate in other, OS-level input buffers.
  2342.  
  2343. 11.12:  How can I redirect stdin or stdout to a file from within a
  2344.         program?
  2345.  
  2346. A:      Use freopen.
  2347.  
  2348. 11.13:  Once I've used freopen, how can I get the original stdout (or
  2349.         stdin) back?
  2350.  
  2351. A:      If you need to switch back and forth, the best all-around
  2352.         solution is not to use freopen in the first place.  Try using
  2353.         your own explicit output (or input) stream variable, which you
  2354.         can reassign at will, while leaving the original stdout (or
  2355.         stdin) undisturbed.
  2356.  
  2357. 11.14:  How can I recover the file name given an open file descriptor?
  2358.  
  2359. A:      This problem is, in general, insoluble.  Under Unix, for
  2360.         instance, a scan of the entire disk, (perhaps requiring special
  2361.         permissions) would theoretically be required, and would fail if
  2362.         the file descriptor was a pipe or referred to a deleted file
  2363.         (and could give a misleading answer for a file with multiple
  2364.         links).  It is best to remember the names of files yourself when
  2365.         you open them (perhaps with a wrapper function around fopen).
  2366.  
  2367.  
  2368. Section 12. Library Subroutines
  2369.  
  2370. 12.1:   Why does strncpy not always place a '\0' termination in the
  2371.         destination string?
  2372.  
  2373. A:      strncpy was first designed to handle a now-obsolete data
  2374.         structure, the fixed-length, not-necessarily-\0-terminated
  2375.         "string."  strncpy is admittedly a bit cumbersome to use in
  2376.         other contexts, since you must often append a '\0' to the
  2377.         destination string by hand.
  2378.  
  2379. 12.2:   I'm trying to sort an array of strings with qsort, using strcmp
  2380.         as the comparison function, but it's not working.
  2381.  
  2382. A:      By "array of strings" you probably mean "array of pointers to
  2383.         char."  The arguments to qsort's comparison function are
  2384.         pointers to the objects being sorted, in this case, pointers to
  2385.         pointers to char.  (strcmp, of course, accepts simple pointers
  2386.         to char.)
  2387.  
  2388.         The comparison routine's arguments are expressed as "generic
  2389.         pointers," const void * or char *.  They must be converted back
  2390.         to what they "really are" (char **) and dereferenced, yielding
  2391.         char *'s which can be usefully compared.  Write a comparison
  2392.         function like this:
  2393.  
  2394.                 int pstrcmp(p1, p2)     /* compare strings through pointers */
  2395.                 char *p1, *p2;          /* const void * for ANSI C */
  2396.                 {
  2397.                         return strcmp(*(char **)p1, *(char **)p2);
  2398.                 }
  2399.  
  2400. 12.3:   Now I'm trying to sort an array of structures with qsort.  My
  2401.         comparison routine takes pointers to structures, but the
  2402.         compiler complains that the function is of the wrong type for
  2403.         qsort.  How can I cast the function pointer to shut off the
  2404.         warning?
  2405.  
  2406. A:      The conversions must be in the comparison function, which must
  2407.         be declared as accepting "generic pointers" (const void * or
  2408.         char *) as discussed above.
  2409.  
  2410. 12.4:   How can I convert numbers to strings (the opposite of atoi)?  Is
  2411.         there an itoa function?
  2412.  
  2413. A:      Just use sprintf.  (You'll have to allocate space for the result
  2414.         somewhere anyway; see questions 3.1 and 3.2.  Don't worry that
  2415.         sprintf may be overkill, potentially wasting run time or code
  2416.         space; it works well in practice.)
  2417.  
  2418.         References: K&R I Sec. 3.6 p. 60; K&R II Sec. 3.6 p. 64.
  2419.  
  2420. 12.5:   How can I get the current date or time of day in a C program?
  2421.  
  2422. A:      Just use the time, ctime, and/or localtime functions.  (These
  2423.         routines have been around for years, and are in the ANSI
  2424.         standard.)  Here is a simple example:
  2425.  
  2426.                 #include <stdio.h>
  2427.                 #include <time.h>
  2428.  
  2429.                 main()
  2430.                 {
  2431.                         time_t now;
  2432.                         time(&now);
  2433.                         printf("It's %.24s.\n", ctime(&now));
  2434.                         return 0;
  2435.                 }
  2436.  
  2437.         References: ANSI Sec. 4.12 .
  2438.  
  2439. 12.6:   I know that the library routine localtime will convert a time_t
  2440.         into a broken-down struct tm, and that ctime will convert a
  2441.         time_t to a printable string.  How can I perform the inverse
  2442.         operations of converting a struct tm or a string into a time_t?
  2443.  
  2444. A:      ANSI C specifies a library routine, mktime, which converts a
  2445.         struct tm to a time_t.  Several public-domain versions of this
  2446.         routine are available in case your compiler does not support it
  2447.         yet.
  2448.  
  2449.         Converting a string to a time_t is harder, because of the wide
  2450.         variety of date and time formats which should be parsed.
  2451.         Public-domain routines have been written for performing this
  2452.         function (see, for example, the file partime.c, widely
  2453.         distributed with the RCS package), but they are less likely to
  2454.         become standardized.
  2455.  
  2456.         References: K&R II Sec. B10 p. 256; H&S Sec. 20.4 p. 361; ANSI
  2457.         Sec. 4.12.2.3 .
  2458.  
  2459. 12.7:   I need a random number generator.
  2460.  
  2461. A:      The standard C library has one: rand().  The implementation on
  2462.         your system may not be perfect, but writing a better one isn't
  2463.         necessarily easy, either.
  2464.  
  2465.         References: ANSI Sec. 4.10.2.1 p. 154, Knuth Vol. 2 Chap. 3
  2466.         pp. 1-177.
  2467.  
  2468. 12.8:   Each time I run my program, I get the same sequence of numbers
  2469.         back from rand().
  2470.  
  2471. A:      You can call srand() to seed the pseudo-random number generator
  2472.         with a more random initial value.  Popular seed values are the
  2473.         time of day, or the elapsed time before the user presses a key
  2474.         (although keypress times are hard to determine portably; see
  2475.         question 16.9).
  2476.  
  2477.         References: ANSI Sec. 4.10.2.2 p. 154.
  2478.  
  2479. 12.9:   I need a random true/false value, so I'm taking rand() % 2, but
  2480.         it's just alternating 0, 1, 0, 1, 0...
  2481.  
  2482. A:      Poor pseudorandom number generators (such as the ones
  2483.         unfortunately supplied with some systems) are not very random in
  2484.         the low-order bits.  Try using the higher-order bits.
  2485.  
  2486. 12.10-  I'm trying to port this old     A:  These routines are variously
  2487.  12.14: program.  Why do I get              obsolete; you should
  2488.         "undefined external" errors         instead:
  2489.         for:
  2490.  
  2491. 12.10:  index?                          A:  use strchr.
  2492. 12.11:  rindex?                         A:  use strrchr.
  2493. 12.12:  bcopy?                          A:  use memmove, after
  2494.                                             interchanging the first and
  2495.                                             second arguments (see also
  2496.                                             question 5.13).
  2497. 12.13:  bcmp?                           A:  use memcmp.
  2498. 12.14:  bzero?                          A:  use memset, with a second
  2499.                                             argument of 0.
  2500.  
  2501. 12.15:  How can I execute a command with system() and read its output
  2502.         into a program?
  2503.  
  2504. A:      Unix and some other systems provide a popen() routine, which
  2505.         sets up a stdio stream on a pipe connected to the process
  2506.         running a command, so that the output can be read (or the input
  2507.         supplied).
  2508.  
  2509. 12.16:  How can I read a directory in a C program?
  2510.  
  2511. A:      See if you can use the opendir() and readdir() routines, which
  2512.         are available on most Unix systems.  Implementations also exist
  2513.         for MS-DOS, VMS, and other systems.  (MS-DOS also has FINDFIRST
  2514.         and FINDNEXT routines which do essentially the same thing.)
  2515.  
  2516.  
  2517. Section 13. Lint
  2518.  
  2519. 13.1:   I just typed in this program, and it's acting strangely.  Can
  2520.         you see anything wrong with it?
  2521.  
  2522. A:      Try running lint first(perhaps with the -a, -c, -h, -p and/or
  2523.         other options).  Many C compilers are really only half-
  2524.         compilers, electing not to diagnose numerous source code
  2525.         difficulties which would not actively preclude code generation.
  2526.  
  2527. 13.2:   How can I shut off the "warning: possible pointer alignment
  2528.         problem" message lint gives me for each call to malloc?
  2529.  
  2530. A:      The problem is that traditional versions of lint do not know,
  2531.         and cannot be told, that malloc "returns a pointer to space
  2532.         suitably aligned for storage of any type of object."  It is
  2533.         possible to provide a pseudoimplementation of malloc, using a
  2534.         #define inside of #ifdef lint, which effectively shuts this
  2535.         warning off, but a simpleminded #definition will also suppress
  2536.         meaningful messages about truly incorrect invocations.  It may
  2537.         be easier simply to ignore the message, perhaps in an automated
  2538.         way with grep -v.
  2539.  
  2540. 13.3:   Where can I get an ANSI-compatible lint?
  2541.  
  2542. A:      A product called FlexeLint is available (in "shrouded source
  2543.         form," for compilation on 'most any system) from
  2544.  
  2545.                 Gimpel Software
  2546.                 3207 Hogarth Lane
  2547.                 Collegeville, PA  19426  USA
  2548.                 (+1) 215 584 4261
  2549.  
  2550.         The System V release 4 lint is ANSI-compatible, and is available
  2551.         separately (bundled with other C tools) from Unix Support Labs
  2552.         (a subsidiary of AT&T), or from System V resellers.
  2553.  
  2554.  
  2555. Section 14. Style
  2556.  
  2557. 14.1:   Here's a neat trick:
  2558.  
  2559.                 if(!strcmp(s1, s2))
  2560.  
  2561.         Is this good style?
  2562.  
  2563. A:      It is not particularly good style, although it is a popular
  2564.         idiom.  The test succeeds if the two strings are equal, but its
  2565.         form suggests that it tests for inequality.
  2566.  
  2567.         Another solution is to use a macro:
  2568.  
  2569.                 #define Streq(s1, s2) (strcmp((s1), (s2)) == 0)
  2570.  
  2571.         Opinions on code style, like those on religion, can be debated
  2572.         endlessly.  Though good style is a worthy goal, and can usually
  2573.         be recognized, it cannot be codified.
  2574.  
  2575. 14.2:   What's the best style for code layout in C?
  2576.  
  2577. A:      K&R, while providing the example most often copied, also supply
  2578.         a good excuse for avoiding it:
  2579.  
  2580.                 The position of braces is less important,
  2581.                 although people hold passionate beliefs.
  2582.                 We have chosen one of several popular styles.
  2583.                 Pick a style that suits you, then use it
  2584.                 consistently.
  2585.  
  2586.         It is more important that the layout chosen be consistent (with
  2587.         itself, and with nearby or common code) than that it be
  2588.         "perfect."  If your coding environment (i.e. local custom or
  2589.         company policy) does not suggest a style, and you don't feel
  2590.         like inventing your own, just copy K&R.  (The tradeoffs between
  2591.         various indenting and brace placement options can be
  2592.         exhaustively and minutely examined, but don't warrant repetition
  2593.         here.  See also the Indian Hill Style Guide.)
  2594.  
  2595.         The elusive quality of "good style" involves much more than mere
  2596.         code layout details; don't spend time on formatting to the
  2597.         exclusion of more substantive code quality issues.
  2598.  
  2599.         References: K&R Sec. 1.2 p. 10.
  2600.  
  2601. 14.3:   Where can I get the "Indian Hill Style Guide" and other coding
  2602.         standards?
  2603.  
  2604. A:      Various documents are available for anonymous ftp from:
  2605.  
  2606.                 Site:                   File or directory:
  2607.  
  2608.                 cs.washington.edu       ~ftp/pub/cstyle.tar.Z
  2609.                 (128.95.1.4)            (the updated Indian Hill guide)
  2610.  
  2611.                 cs.toronto.edu          doc/programming
  2612.  
  2613.                 giza.cis.ohio-state.edu pub/style-guide
  2614.  
  2615.  
  2616. Section 15. Floating Point
  2617.  
  2618. 15.1:   My floating-point calculations are acting strangely and giving
  2619.         me different answers on different machines.
  2620.  
  2621. A:      First, make sure that you have #included <math.h>, and correctly
  2622.         declared other functions returning double.
  2623.  
  2624.         If the problem isn't that simple, recall that most digital
  2625.         computers use floating-point formats which provide a close but
  2626.         by no means exact simulation of real number arithmetic.
  2627.         Underflow, cumulative precision loss, and other anomalies are
  2628.         often troublesome.
  2629.  
  2630.         Don't assume that floating-point results will be exact, and
  2631.         especially don't assume that floating-point values can be
  2632.         compared for equality.  (Don't throw haphazard "fuzz factors"
  2633.         in, either.)
  2634.  
  2635.         These problems are no worse for C than they are for any other
  2636.         computer language.  Floating-point semantics are usually defined
  2637.         as "however the processor does them;" otherwise a compiler for a
  2638.         machine without the "right" model would have to do prohibitively
  2639.         expensive emulations.
  2640.  
  2641.         This article cannot begin to list the pitfalls associated with,
  2642.         and workarounds appropriate for, floating-point work.  A good
  2643.         programming text should cover the basics.
  2644.  
  2645.         References: EoPS Sec. 6 pp. 115-8.
  2646.  
  2647. 15.2:   I'm trying to do some simple trig, and I am #including <math.h>,
  2648.         but I keep getting "undefined: _sin" compilation errors.
  2649.  
  2650. A:      Make sure you're linking against the correct math library.  For
  2651.         instance, under Unix, you usually need to use the -lm option,
  2652.         and at the _end_ of the command line, when compiling/linking.
  2653.  
  2654. 15.3:   Why doesn't C have an exponentiation operator?
  2655.  
  2656. A:      You can #include <math.h> and use the pow() function, although
  2657.         explicit multiplication is often better for small positive
  2658.         integral exponents.
  2659.  
  2660.         References: ANSI Sec. 4.5.5.1 .
  2661.  
  2662. 15.4:   I'm having trouble with a Turbo C program which crashes and says
  2663.         something like "floating point formats not linked."
  2664.  
  2665. A:      Some compilers for small machines, including Turbo C (and
  2666.         Ritchie's original PDP-11 compiler), leave out floating point
  2667.         support if it looks like it will not be needed.  In particular,
  2668.         the non-floating-point versions of printf and scanf save space
  2669.         by not including code to handle %e, %f, and %g.  It happens that
  2670.         Turbo C's heuristics for determining whether the program uses
  2671.         floating point are insufficient, and the programmer must
  2672.         sometimes insert an extra, explicit call to a floating-point
  2673.         library routine to force loading of floating-point support.
  2674.  
  2675.  
  2676. Section 16. System Dependencies
  2677.  
  2678. 16.1:   How can I read a single character from the keyboard without
  2679.         waiting for a newline?
  2680.  
  2681. A:      Contrary to popular belief and many people's wishes, this is not
  2682.         a C-related question.  (Nor are closely-related questions
  2683.         concerning the echo of keyboard input.)  The delivery of
  2684.         characters from a "keyboard" to a C program is a function of the
  2685.         operating system in use, and has not been standardized by the C
  2686.         language.  Some versions of curses have a cbreak() function
  2687.         which does what you want.  Under UNIX, use ioctl to play with
  2688.         the terminal driver modes (CBREAK or RAW under "classic"
  2689.         versions; ICANON, c_cc[VMIN] and c_cc[VTIME] under System V or
  2690.         Posix systems).  Under MS-DOS, use getch().  Under VMS, try the
  2691.         Screen Management (SMG$) routines, or curses, or issue low-level
  2692.         $QIO's to ask for one character at a time.  Under other
  2693.         operating systems, you're on your own.  Beware that some
  2694.         operating systems make this sort of thing impossible, because
  2695.         character collection into input lines is done by peripheral
  2696.         processors not under direct control of the CPU running your
  2697.         program.
  2698.  
  2699.         Operating system specific questions are not appropriate for
  2700.         comp.lang.c .  Many common questions are answered in
  2701.         frequently-asked questions postings in such groups as
  2702.         comp.unix.questions and comp.os.msdos.programmer .  Note that
  2703.         the answers are often not unique even across different variants
  2704.         of a system; bear in mind when answering system-specific
  2705.         questions that the answer that applies to your system may not
  2706.         apply to everyone else's.
  2707.  
  2708.         References: PCS Sec. 10 pp. 128-9, Sec. 10.1 pp. 130-1.
  2709.  
  2710. 16.2:   How can I find out if there are characters available for reading
  2711.         (and if so, how many)?  Alternatively, how can I do a read that
  2712.         will not block if there are no characters available?
  2713.  
  2714. A:      These, too, are entirely operating-system-specific.  Some
  2715.         versions of curses have a nodelay() function.  Depending on your
  2716.         system, you may also be able to use "nonblocking I/O", or a
  2717.         system call named "select", or the FIONREAD ioctl, or kbhit(),
  2718.         or rdchk(), or the O_NDELAY option to open() or fcntl().
  2719.  
  2720. 16.3:   How can I clear the screen?  How can I print things in inverse
  2721.         video?
  2722.  
  2723. A:      Such things depend on the terminal type (or display) you're
  2724.         using.  You will have to use a library such as termcap or
  2725.         curses, or some system-specific routines, to perform these
  2726.         functions.
  2727.  
  2728. 16.4:   How do I read the mouse?
  2729.  
  2730. A:      Consult your system documentation, or ask on an appropriate
  2731.         system-specific newsgroup (but check its FAQ list first).  Mouse
  2732.         handling is completely different under the X window system, MS-
  2733.         DOS, Macintosh, and probably every other system.
  2734.  
  2735. 16.5:   How can my program discover the complete pathname to the
  2736.         executable file from which it was invoked?
  2737.  
  2738. A:      argv[0] may contain all or part of the pathname, or it may
  2739.         contain nothing.  You may be able to duplicate the command
  2740.         language interpreter's search path logic to locate the
  2741.         executable if the name in argv[0] is present but incomplete.
  2742.         However, there is no guaranteed or portable solution.
  2743.  
  2744. 16.6:   How can a process change an environment variable in its caller?
  2745.  
  2746. A:      In general, it cannot.  Different operating systems implement
  2747.         name/value functionality similar to the Unix environment in
  2748.         different ways.  Whether the "environment" can be usefully
  2749.         altered by a running program, and if so, how, is system-
  2750.         dependent.
  2751.  
  2752.         Under Unix, a process can modify its own environment (some
  2753.         systems provide setenv() and/or putenv() functions to do this),
  2754.         and the modified environment is usually passed on to any child
  2755.         processes, but it is _not_ propagated back to the parent
  2756.         process.
  2757.  
  2758. 16.7:   How can I find out the size of a file, prior to reading it in?
  2759.  
  2760. A:      If the "size of a file" is the number of characters you'll be
  2761.         able to read from it in C, it is in general impossible to
  2762.         determine this number in advance.  Under Unix, the stat call
  2763.         will give you an exact answer, and several other systems supply
  2764.         a Unix-like stat which will give an approximate answer.  You can
  2765.         fseek to the end and then use ftell, but this usage is
  2766.         nonportable (it gives you an accurate answer only under Unix,
  2767.         and otherwise a quasi-accurate answer only for ANSI C "binary"
  2768.         files).
  2769.  
  2770.         Are you sure you have to determine the file's size in advance?
  2771.         Since the most accurate way of determining the size of a file as
  2772.         a C program will see it is to open the file and read it, perhaps
  2773.         you can rearrange the code to learn the size as it reads.
  2774.  
  2775. 16.8:   How can a file be shortened in-place without completely clearing
  2776.         or rewriting it?
  2777.  
  2778. A:      BSD systems provide ftruncate(), several others supply chsize(),
  2779.         and a few may provide a (possibly undocumented) fcntl option
  2780.         F_FREESP.  Under MS-DOS, you can sometimes use write(fd, "", 0).
  2781.         However, there is no truly portable solution.
  2782.  
  2783. 16.9:   How can I implement a delay, or time a user's response, with
  2784.         sub-second resolution?
  2785.  
  2786. A:      Unfortunately, there is no portable way.  V7 Unix, and derived
  2787.         systems, provided a fairly useful ftime() routine with
  2788.         resolution up to a millisecond, but it has disappeared from
  2789.         System V and Posix.  Other routines you might look for on your
  2790.         system include clock() and gettimeofday().  The select() and
  2791.         poll() calls (if available) can be pressed into service to
  2792.         implement simple delays.  On MS-DOS machines, it is possible to
  2793.         reprogram the system timer and timer interrupts.
  2794.  
  2795. 16.10:  How can I read in an object file and jump to routines in it?
  2796.  
  2797. A:      You want a dynamic linker and/or loader.  It is possible to
  2798.         malloc some space and read in object files, but you have to know
  2799.         an awful lot about object file formats, relocation, etc.  Under
  2800.         BSD Unix, you could use system() and ld -A to do the linking for
  2801.         you.  Many (most?) versions of SunOS and System V have the -ldl
  2802.         library which allows object files to be dynamically loaded.
  2803.         There is also a GNU package called "dld".  See also question
  2804.         7.6.
  2805.  
  2806.  
  2807. Section 17. Miscellaneous
  2808.  
  2809. 17.1:   What can I safely assume about the initial values of variables
  2810.         which are not explicitly initialized?  If global variables start
  2811.         out as "zero," is that good enough for null pointers and
  2812.         floating-point zeroes?
  2813.  
  2814. A:      Variables with "static" duration (that is, those declared
  2815.         outside of functions, and those declared with the storage class
  2816.         static), are guaranteed initialized to zero, as if the
  2817.         programmer had typed "= 0".  Therefore, such variables are
  2818.         initialized to the null pointer (of the correct type) if they
  2819.         are pointers, and to 0.0 if they are floating-point.
  2820.  
  2821.         Variables with "automatic" duration (i.e. local variables
  2822.         without the static storage class) start out containing garbage,
  2823.         unless they are explicitly initialized.  Nothing useful can be
  2824.         predicted about the garbage.
  2825.  
  2826.         Dynamically-allocated memory obtained with malloc and realloc is
  2827.         also likely to contain garbage, and must be initialized by the
  2828.         calling program, as appropriate.  Memory obtained with calloc
  2829.         contains all-bits-0, but this is not necessarily useful for
  2830.         pointer or floating-point values (see question 3.11, and section
  2831.         1).
  2832.  
  2833. 17.2:   How can I write data files which can be read on other machines
  2834.         with different word size, byte order, or floating point formats?
  2835.  
  2836. A:      The best solution is to use text files (usually ASCII), written
  2837.         with fprintf and read with fscanf or the like.  (Similar advice
  2838.         also applies to network protocols.)  Be skeptical of arguments
  2839.         which imply that text files are too big, or that reading and
  2840.         writing them is too slow.  Not only is their efficiency
  2841.         frequently acceptable in practice, but the advantages of being
  2842.         able to manipulate them with standard tools can be overwhelming.
  2843.         If you must use a binary format, you can improve portability,
  2844.         and perhaps take advantage of prewritten I/O libraries, by
  2845.         making use of standardized formats such as Sun's XDR (RFC 1014),
  2846.         OSI's ASN.1, CCITT's X.409, or ISO 8825 "Basic Encoding Rules."
  2847.         See also question 9.10.
  2848.  
  2849. 17.3:   How can I return several values from a function?
  2850.  
  2851. A:      Either pass pointers to locations which the function can fill
  2852.         in, or have the function return a structure containing the
  2853.         desired values, or (in a pinch) consider global variables.  See
  2854.         also questions 2.16, 3.4, and 9.2.
  2855.  
  2856. 17.4:   If I have a char * variable pointing to the name of a function
  2857.         as a string, how can I call that function?
  2858.  
  2859. A:      The most straightforward thing to do is maintain a
  2860.         correspondence table of names and function pointers:
  2861.  
  2862.                 int function1(), function2();
  2863.  
  2864.                 struct {char *name; int (*funcptr)(); } symtab[] =
  2865.                         {
  2866.                         "function1",    function1,
  2867.                         "function2",    function2,
  2868.                         };
  2869.  
  2870.         Then, just search the table for the name, and call through the
  2871.         associated function pointer.
  2872.  
  2873. 17.5:   I seem to be missing the system header file <sgtty.h>.  Can
  2874.         someone send me a copy?
  2875.  
  2876. A:      Standard headers exist in part so that definitions appropriate
  2877.         to your compiler, operating system, and processor can be
  2878.         supplied.  You cannot just pick up a copy of someone else's
  2879.         header file and expect it to work, unless that person is using
  2880.         exactly the same environment.  Ask your compiler vendor why the
  2881.         file was not provided (or to send a replacement copy).
  2882.  
  2883. 17.6:   How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP) functions
  2884.         from C?  (And vice versa?)
  2885.  
  2886. A:      The answer is entirely dependent on the machine and the specific
  2887.         calling sequences of the various compilers in use, and may not
  2888.         be possible at all.  Read your compiler documentation very
  2889.         carefully; sometimes there is a "mixed-language programming
  2890.         guide," although the techniques for passing arguments and
  2891.         ensuring correct run-time startup are often arcane.  More
  2892.         information may be found in FORT.Z by Glenn Geers, available via
  2893.         anonymous ftp from suphys.physics.su.oz.au in the src directory.
  2894.  
  2895.         cfortran.h, a C header file, simplifies C/FORTRAN interfacing on
  2896.         many popular machines.  It is available via anonymous ftp from
  2897.         zebra.desy.de (131.169.2.244).
  2898.  
  2899.         In C++, a "C" modifier in an external function declaration
  2900.         indicates that the function is to be called using C calling
  2901.         conventions.
  2902.  
  2903. 17.7:   Does anyone know of a program for converting Pascal or FORTRAN
  2904.         (or LISP, Ada, awk, "Old" C, ...) to C?
  2905.  
  2906. A:      Several public-domain programs are available:
  2907.  
  2908.         p2c     written by Dave Gillespie, and posted to
  2909.                 comp.sources.unix in March, 1990 (Volume 21); also
  2910.                 available by anonymous ftp from csvax.cs.caltech.edu,
  2911.                 file pub/p2c-1.20.tar.Z .
  2912.  
  2913.         ptoc    another comp.sources.unix contribution, this one written
  2914.                 in Pascal (comp.sources.unix, Volume 10, also patches in
  2915.                 Volume 13?).
  2916.  
  2917.         f2c     jointly developed by people from Bell Labs, Bellcore,
  2918.                 and Carnegie Mellon.  To find about f2c, send the mail
  2919.                 message "send index from f2c" to netlib@research.att.com
  2920.                 or research!netlib.  (It is also available via anonymous
  2921.                 ftp on research.att.com, in directory dist/f2c.)
  2922.  
  2923.         This FAQ list's maintainer also has available a list of other
  2924.         commercial translation products, and some for more obscure
  2925.         languages.
  2926.  
  2927.         See also question 5.3.
  2928.  
  2929. 17.8:   Where can I get copies of all these public-domain programs?
  2930.  
  2931. A:      If you have access to Usenet, see the regular postings in the
  2932.         comp.sources.unix and comp.sources.misc newsgroups, which
  2933.         describe, in some detail, the archiving policies and how to
  2934.         retrieve copies.  The usual approach is to use anonymous ftp
  2935.         and/or uucp from a central, public-spirited site, such as uunet
  2936.         (ftp.uu.net, 192.48.96.9).  However, this article cannot track
  2937.         or list all of the available archive sites and how to access
  2938.         them.  The comp.archives newsgroup contains numerous
  2939.         announcements of anonymous ftp availability of various items.
  2940.         The "archie" mailserver can tell you which anonymous ftp sites
  2941.         have which packages; send the mail message "help" to
  2942.         archie@quiche.cs.mcgill.ca for information.  Finally, the
  2943.         newsgroup comp.sources.wanted is generally a more appropriate
  2944.         place to post queries for source availability, but check _its_
  2945.         FAQ list, "How to find sources," before posting there.
  2946.  
  2947. 17.9:   When will the next International Obfuscated C Code Contest
  2948.         (IOCCC) be held?  How can I get a copy of the current and
  2949.         previous winning entries?
  2950.  
  2951. A:      The contest typically runs from early March through mid-May.  To
  2952.         obtain a current copy of the rules and guidelines, send e-mail
  2953.         with the Subject: line "send rules" to:
  2954.  
  2955.                 {apple,pyramid,sun,uunet}!hoptoad!judges  (not the addresses for
  2956.         or      judges@toad.com                            submitting entries)
  2957.  
  2958.         Contest winners are first announced at the Summer Usenix
  2959.         Conference in mid-June, and posted to the net sometime in July-
  2960.         August.  Winning entries from previous years (to 1984) are
  2961.         archived at uunet (see question 17.8) under the directory
  2962.         ~/pub/ioccc.
  2963.  
  2964.         As a last resort, previous winners may be obtained by sending
  2965.         e-mail to the above address, using the Subject: "send YEAR
  2966.         winners", where YEAR is a single four-digit year, a year range,
  2967.         or "all".
  2968.  
  2969. 17.10:  Why don't C comments nest?  Are they legal inside quoted
  2970.         strings?
  2971.  
  2972. A:      Nested comments would cause more harm than good, mostly because
  2973.         of the possibility of accidentally leaving comments unclosed by
  2974.         including the characters "/*" within them.  For this reason, it
  2975.         is usually better to "comment out" large sections of code, which
  2976.         might contain comments, with #ifdef or #if 0 (but see question
  2977.         5.9).
  2978.  
  2979.         The character sequences /* and */ are not special within
  2980.         double-quoted strings, and do not therefore introduce comments,
  2981.         because a program (particularly one which is generating C code
  2982.         as output) might want to print them.
  2983.  
  2984.         References: ANSI Appendix E p. 198, Rationale Sec. 3.1.9 p. 33.
  2985.  
  2986. 17.11:  How can I implement sets and/or arrays of bits?
  2987.  
  2988. A:      Use arrays of char or int, with a few macros to access the right
  2989.         bit at the right index (try using 8 for CHAR_BIT if you don't
  2990.         have <limits.h>):
  2991.  
  2992.                 #include <limits.h>             /* for CHAR_BIT */
  2993.  
  2994.                 #define BITMASK(bit) (1 << ((bit) % CHAR_BIT))
  2995.                 #define BITSLOT(bit) ((bit) / CHAR_BIT)
  2996.                 #define BITSET(ary, bit) ((ary)[BITSLOT(bit)] |= BITMASK(bit))
  2997.                 #define BITTEST(ary, bit) ((ary)[BITSLOT(bit)] & BITMASK(bit))
  2998.  
  2999. 17.12:  What is the most efficient way to count the number of bits which
  3000.         are set in a value?
  3001.  
  3002. A:      This and many other similar bit-twiddling problems can often be
  3003.         sped up and streamlined using lookup tables (but see the next
  3004.         question).
  3005.  
  3006. 17.13:  How can I make this code more efficient?
  3007.  
  3008. A:      Efficiency, though a favorite comp.lang.c topic, is not
  3009.         important nearly as often as people tend to think it is.  Most
  3010.         of the code in most programs is not time-critical.  When code is
  3011.         not time-critical, it is far more important that it be written
  3012.         clearly and portably than that it be written maximally
  3013.         efficiently.  (Remember that computers are very, very fast, and
  3014.         that even "inefficient" code can run without apparent delay.)
  3015.  
  3016.         It is notoriously difficult to predict what the "hot spots" in a
  3017.         program will be.  When efficiency is a concern, it is important
  3018.         to use profiling software to determine which parts of the
  3019.         program deserve attention.  Often, actual computation time is
  3020.         swamped by peripheral tasks such as I/O and memory allocation,
  3021.         which can be sped up by using buffering and cacheing techniques.
  3022.  
  3023.         For the small fraction of code that is time-critical, it is
  3024.         vital to pick a good algorithm; it is less important to
  3025.         "microoptimize" the coding details.  Many of the "efficient
  3026.         coding tricks" which are frequently suggested (e.g. substituting
  3027.         shift operators for multiplication by powers of two) are
  3028.         performed automatically by even simpleminded compilers.
  3029.         Heavyhanded "optimization" attempts can make code so bulky that
  3030.         performance is degraded.
  3031.  
  3032.         For more discussion of efficiency tradeoffs, as well as good
  3033.         advice on how to increase efficiency when it is important, see
  3034.         chapter 7 of Kernighan and Plauger's The Elements of Programming
  3035.         Style, and Jon Bentley's Writing Efficient Programs.
  3036.  
  3037. 17.14:  Are pointers really faster than arrays?  How much do function
  3038.         calls slow things down?  Is ++i faster than i = i + 1?
  3039.  
  3040. A:      Precise answers to these and many similar questions depend of
  3041.         course on the processor and compiler in use.  If you simply must
  3042.         know, you'll have to time test programs carefully.  (Often the
  3043.         differences are so slight that hundreds of thousands of
  3044.         iterations are required even to see them.  Check the compiler's
  3045.         assembly language output, if available, to see if two purported
  3046.         alternatives aren't compiled identically.)
  3047.  
  3048.         It is "usually" faster to march through large arrays with
  3049.         pointers rather than array subscripts, but for some processors
  3050.         the reverse is true.
  3051.  
  3052.         Function calls, though obviously incrementally slower than in-
  3053.         line code, contribute so much to modularity and code clarity
  3054.         that there is rarely good reason to avoid them.
  3055.  
  3056.         Before rearranging expressions such as i = i + 1, remember that
  3057.         you are dealing with a C compiler, not a keystroke-programmable
  3058.         calculator.  Any decent compiler will generate identical code
  3059.         for ++i, i += 1, and i = i + 1.  The reasons for using ++i or
  3060.         i += 1 over i = i + 1 have to do with style, not efficiency.
  3061.         (See also question 4.4.)
  3062.  
  3063. 17.15:  This program crashes before it even runs!  (When single-stepping
  3064.         with a debugger, it dies before the first statement in main.)
  3065.  
  3066. A:      You probably have one or more very large (kilobyte or more)
  3067.         local arrays.  Many systems have fixed-size stacks, and those
  3068.         which perform dynamic stack allocation automatically (e.g. Unix)
  3069.         can be confused when the stack tries to grow by a huge chunk all
  3070.         at once.
  3071.  
  3072.         It is often better to declare large arrays with static duration
  3073.         (unless of course you need a fresh set with each recursive
  3074.         call).
  3075.  
  3076.         (See also question 9.4.)
  3077.  
  3078. 17.16:  What do "Segmentation violation" and "Bus error" mean?
  3079.  
  3080. A:      These generally mean that your program tried to access memory it
  3081.         shouldn't have, invariably as a result of improper pointer use,
  3082.         often involving malloc (see question 17.17) or perhaps scanf
  3083.         (see question 11.2).
  3084.  
  3085. 17.17:  My program is crashing, apparently somewhere down inside malloc,
  3086.         but I can't see anything wrong with it.
  3087.  
  3088. A:      It is unfortunately very easy to corrupt malloc's internal data
  3089.         structures, and the resulting problems can be hard to track
  3090.         down.  The most common source of problems is writing more to a
  3091.         malloc'ed region than it was allocated to hold; a particularly
  3092.         common bug is to malloc(strlen(s)) instead of strlen(s) + 1.
  3093.         Other problems involve freeing pointers not obtained from
  3094.         malloc, or trying to realloc a null pointer (see question 3.10).
  3095.  
  3096.         A number of debugging packages exist to help track down malloc
  3097.         problems; one popular one is Conor P. Cahill's "dbmalloc".
  3098.  
  3099. 17.18:  Does anyone have a C compiler test suite I can use?
  3100.  
  3101. A:      Plum Hall (1 Spruce Ave., Cardiff, NJ 08232, USA) sells one.
  3102.         The FSF's GNU C (gcc) distribution includes a c-torture-
  3103.         test.tar.Z which checks a number of common problems with
  3104.         compilers.  Kahan's paranoia test, found in netlib on
  3105.         research.att.com, strenuously tests a C implementation's
  3106.         floating point capabilities.
  3107.  
  3108. 17.19:  Where can I get a YACC grammar for C?
  3109.  
  3110. A:      The definitive grammar is of course the one in the ANSI
  3111.         standard.  Several copies are floating around; keep your eyes
  3112.         open.  There is one (due to Jeff Lee) on uunet (see question
  3113.         17.8) in usenet/net.sources/ansi.c.grammar.Z (including a
  3114.         companion lexer).  Another one, by Jim Roskind, is in
  3115.         pub/*grammar* at ics.uci.edu .  The FSF's GNU C compiler
  3116.         contains a grammar, as does the appendix to K&R II.
  3117.  
  3118.         References: ANSI Sec. A.2 .
  3119.  
  3120. 17.20:  How do you pronounce "char"?
  3121.  
  3122. A:      You can pronounce the C keyword "char" in at least three ways:
  3123.         like the English words "char," "care," or "car;" the choice is
  3124.         arbitrary.
  3125.  
  3126. 17.21:  What's a good book for learning C?
  3127.  
  3128. A:      Mitch Wright maintains an annotated bibliography of C and Unix
  3129.         books; it is available for anonymous ftp from ftp.rahul.net in
  3130.         directory pub/mitch/YABL.
  3131.  
  3132.         This FAQ list's editor maintains a collection of previous
  3133.         answers to this question, which is available upon request.
  3134.  
  3135. 17.22:  Where can I get extra copies of this list?  What about back
  3136.         issues?
  3137.  
  3138. A:      For now, just pull it off the net; it is normally posted to
  3139.         comp.lang.c on the first of each month, with an Expiration: line
  3140.         which should keep it around all month.  It can also be found in
  3141.         the newsgroups comp.answers and news.answers .  Several sites
  3142.         archive news.answers postings and other FAQ lists, including
  3143.         this one: two sites are pit-manager.mit.edu (directory
  3144.         pub/usenet), and ftp.uu.net (directory usenet).  The archie
  3145.         server should help you find others.  See the meta-FAQ list in
  3146.         news.answers for more information; see also question 17.8.
  3147.  
  3148.         This list is an evolving document of questions which have been
  3149.         Frequent since before the Great Renaming, not just a collection
  3150.         of this month's interesting questions.  Older copies are
  3151.         obsolete and don't contain much, except the occasional typo,
  3152.         that the current list doesn't.
  3153.  
  3154.  
  3155. Bibliography
  3156.  
  3157. ANSI    American National Standard for Information Systems --
  3158.         Programming Language -- C, ANSI X3.159-1989 (see question 5.2).
  3159.  
  3160. JLB     Jon Louis Bentley, Writing Efficient Programs, Prentice-Hall,
  3161.         1982, ISBN 0-13-970244-X.
  3162.  
  3163. H&S     Samuel P. Harbison and Guy L. Steele, C: A Reference Manual,
  3164.         Second Edition, Prentice-Hall, 1987, ISBN 0-13-109802-0.
  3165.         (A third edition has recently been released.)
  3166.  
  3167. PCS     Mark R. Horton, Portable C Software, Prentice Hall, 1990,
  3168.         ISBN 0-13-868050-7.
  3169.  
  3170. EoPS    Brian W. Kernighan and P.J. Plauger, The Elements of Programming
  3171.         Style, Second Edition, McGraw-Hill, 1978, ISBN 0-07-034207-5.
  3172.  
  3173. K&R I   Brian W. Kernighan and Dennis M. Ritchie, The C Programming
  3174.         Language, Prentice Hall, 1978, ISBN 0-13-110163-3.
  3175.  
  3176. K&R II  Brian W. Kernighan and Dennis M. Ritchie, The C Programming
  3177.         Language, Second Edition, Prentice Hall, 1988, ISBN 0-13-
  3178.         110362-8, 0-13-110370-9.
  3179.  
  3180. Knuth   Donald E. Knuth, The Art of Computer Programming, (3 vols.),
  3181.         Addison Wesley, 1981.
  3182.  
  3183. CT&P    Andrew Koenig, C Traps and Pitfalls, Addison-Wesley, 1989,
  3184.         ISBN 0-201-17928-8.
  3185.  
  3186.         P.J. Plauger, The Standard C Library, Prentice Hall, 1992,
  3187.         ISBN 0-13-131509-9.
  3188.  
  3189.         Harry Rabinowitz and Chaim Schaap, Portable C, Prentice-Hall,
  3190.         1990, ISBN 0-13-685967-4.
  3191.  
  3192. There is a more extensive bibliography in the revised Indian Hill style
  3193. guide (see question 14.3).  See also question 17.21.
  3194.  
  3195.  
  3196. Acknowledgements
  3197.  
  3198. Thanks to Jamshid Afshar, Sudheer Apte, Randall Atkinson, Dan Bernstein,
  3199. Vincent Broman, Stan Brown, Joe Buehler, Gordon Burditt, Burkhard Burow,
  3200. D'Arcy J.M. Cain, Raymond Chen, Christopher Calabrese, Paul Carter,
  3201. James Davies, Jutta Degener, Norm Diamond, Ray Dunn, Stephen M. Dunn,
  3202. Bjorn Engsig, Alexander Forst, Jeff Francis, Dave Gillespie, Samuel
  3203. Goldstein, Alasdair Grant, Ron Guilmette, Doug Gwyn, Tony Hansen, Joe
  3204. Harrington, Guy Harris, Jos Horsmeier, Blair Houghton, Kirk Johnson,
  3205. Peter Klausler, Andrew Koenig, Tom Koenig, John Lauro, Felix Lee, Don
  3206. Libes, Christopher Lott, Tim McDaniel, John R. MacMillan, Evan Manning,
  3207. Barry Margolin, Brad Mears, Mark Moraes, Darren Morby, Landon Curt Noll,
  3208. David O'Brien, Richard A. O'Keefe, Hans Olsson, Francois Pinard, Pat
  3209. Rankin, Erkki Ruohtula, Rich Salz, Chip Salzenberg, Paul Sand, Doug
  3210. Schmidt, Patricia Shanahan, Peter da Silva, Joshua Simons, Henry
  3211. Spencer, David Spuler, Erik Talvola, Clarke Thatcher, Wayne Throop,
  3212. Chris Torek, Goran Uddeborg, Wietse Venema, Ed Vielmetti, Larry Virden,
  3213. Chris Volpe, Freek Wiedijk, Dave Wolverton, Mitch Wright, Conway Yee,
  3214. and Zhuo Zang, who have contributed, directly or indirectly, to this
  3215. article.  Special thanks to Karl Heuer, and particularly to Mark Brader,
  3216. who (to borrow a line from Steve Johnson) have goaded me beyond my
  3217. inclination, and occasionally beyond my endurance, in relentless pursuit
  3218. of a better FAQ list.
  3219.  
  3220.                                         Steve Summit
  3221.                                         scs@adam.mit.edu
  3222.                                         scs%adam.mit.edu@mit.edu
  3223.                                         mit-eddie!adam.mit.edu!scs
  3224.  
  3225. This article is Copyright 1988, 1990-1993 by Steve Summit.
  3226. It may be freely redistributed so long as the author's name, and this
  3227. notice, are retained.
  3228. The C code in this article (vstrcat(), error(), etc.) is public domain
  3229. and may be used without restriction.
  3230.  
  3231.  
  3232.  
  3233.